ImageUri from Drawable Folder - image

I have been following this tutorial to learn how to implement Pinch Zoom and Pan capabilities into an app I am developing.
https://www.youtube.com/watch?v=BY8hLhu50po&list=PL9jCwTXYWjDJjDE_JxRozYGKGt8gbUXg7
Basically, he loads an image from the gallery and displays it in an image view that supports Zoom/Pan functionality.
I would like to preload an image into the image view rather than select one from the gallery. Ideally, I'd like to load an image from drawable.
The tutorial's app had a lot of extra features that I am trying to weed out.
First it opens a gallery. Then you select an image to display, and it displays it as a thumbnail inside of mImageView.
On Long Click, it hides mImageView and displays a maximized image inside of a second Image View. (MPinchZoomImageView)
At this point, the image supports zoom and pan functionality.
If I could, I'd like to skip the gallery and the first Image View and only use the PinchZoom Image View. I'm not sure how I'd do that.
Code:
ImageViewMainActivity
public class ImageViewMainActivity extends AppCompatActivity {
ImageView mImageView;
PinchZoomImageView mPinchZoomImageView;
private Uri mImageUri;
private static final int REQUEST_OPEN_RESULT_CODE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_view_main);
mImageView = (ImageView) findViewById(R.id.imageView);
mPinchZoomImageView = (PinchZoomImageView) findViewById(R.id.pinchZoomImageView);
mImageView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
pinchZoomPan();
return true;
}
});
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_OPEN_RESULT_CODE); // pass it a context of 0
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
View decorView = getWindow().getDecorView();
if(hasFocus) {
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if(requestCode == REQUEST_OPEN_RESULT_CODE && resultCode == RESULT_OK) {
if(resultData != null) {
mImageUri = resultData.getData();
Glide.with(this)
.load(mImageUri)
.into(mImageView);
}
}
}
private void pinchZoomPan() {
mPinchZoomImageView.setImageUri(mImageUri);
mImageView.setAlpha(0.f); // set mImageView invisible.
mPinchZoomImageView.setVisibility(View.VISIBLE);
}
}
PinchZoomImageView
public class PinchZoomImageView extends ImageView {
private Bitmap mBitmap;
private int mImageWidth;
private int mImageHeight;
private final static float mMinZoom = 1.f;
private final static float mMaxZoom = 4.f;
private float mScaleFactor = 1.f;
private ScaleGestureDetector mScaleGestureDetector;
private final static int NONE = 0;
private final static int PAN = 1;
private final static int ZOOM = 2;
private int mEventState;
private float mStartX = 0;
private float mStartY = 0;
private float mTranslateX = 0;
private float mTranslateY = 0;
private float mPreviousTranslateX = 0;
private float mPreviousTranslateY = 0;
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor();
mScaleFactor = Math.max(mMinZoom, Math.min(mMaxZoom, mScaleFactor));
// invalidate();
// requestLayout();
return super.onScale(detector);
}
}
public PinchZoomImageView(Context context, AttributeSet attrs) {
super(context, attrs);
mScaleGestureDetector = new ScaleGestureDetector(getContext(), new ScaleListener());
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch(event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mEventState = PAN;
mStartX = event.getX() - mPreviousTranslateX;
mStartY = event.getY() - mPreviousTranslateY;
break;
case MotionEvent.ACTION_UP:
mEventState = NONE;
mPreviousTranslateX = mTranslateX;
mPreviousTranslateY = mTranslateY;
break;
case MotionEvent.ACTION_MOVE:
mTranslateX = event.getX() - mStartX;
mTranslateY = event.getY() - mStartY;
break;
case MotionEvent.ACTION_POINTER_DOWN:
mEventState = ZOOM;
break;
}
mScaleGestureDetector.onTouchEvent(event);
if((mEventState == PAN && mScaleFactor != mMinZoom) || mEventState == ZOOM) { // called under the condition that window is zoomed i
invalidate();
requestLayout();
}
return true;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int imageWidth = MeasureSpec.getSize(widthMeasureSpec);
int imageHeight = MeasureSpec.getSize(heightMeasureSpec);
int scaledWidth = Math.round(mImageWidth * mScaleFactor);
int scaledHeight = Math.round(mImageHeight * mScaleFactor);
setMeasuredDimension(
Math.min(imageWidth, scaledWidth),
Math.min(imageHeight, scaledHeight)
);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
canvas.scale(mScaleFactor, mScaleFactor);
// canvas.scale(mScaleFactor, mScaleFactor, mScaleGestureDetector.getFocusX(), mScaleGestureDetector.getFocusY());
if((mTranslateX * -1) < 0) {
mTranslateX = 0;
} else if ((mTranslateX * -1) > mImageWidth * mScaleFactor - getWidth()) {
mTranslateX = (mImageWidth * mScaleFactor - getWidth()) * -1;
}
if((mTranslateY * -1) < 0) {
mTranslateY = 0;
} else if ((mTranslateY * -1) > mImageHeight * mScaleFactor - getHeight()) {
mTranslateY = (mImageHeight * mScaleFactor - getHeight()) * -1;
}
canvas.translate(mTranslateX/mScaleFactor, mTranslateY/mScaleFactor);
canvas.drawBitmap(mBitmap, 0, 0, null);
canvas.restore();
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
public void setImageUri(Uri uri) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), uri);
float aspecRatio = (float) bitmap.getHeight() / (float) bitmap.getWidth();
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
mImageWidth = displayMetrics.widthPixels;
mImageHeight = Math.round(mImageWidth * aspecRatio);
mBitmap = Bitmap.createScaledBitmap(bitmap, mImageWidth, mImageHeight, false);
invalidate();
requestLayout();
} catch (IOException e) {
e.printStackTrace();
}
}
}
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="mobapptut.com.imageviewer.ImageViewMainActivity">
<ImageView
android:layout_width="200dp"
android:layout_height="150dp"
android:id="#+id/imageView"
android:layout_centerInParent="true" />
<mobapptut.com.imageviewer.PinchZoomImageView
android:visibility="invisible"
android:id="#+id/pinchZoomImageView"
android:layout_centerInParent="true"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Thank You

Related

how to align face contour properly in firebase mlkit?

i saw a lot of examples and tried creating a face contouring app and everything worked as expected but for whatsoever reason the dots are not being aligned with the actual face.
here is my activity code
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.otaliastudios.cameraview.CameraView
android:id="#+id/cvv"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:cameraFacing="front"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" >
<com.kirtu.simpletexts.texts.OverlayView
android:id="#+id/overlayView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true" />
</com.otaliastudios.cameraview.CameraView>
</android.support.constraint.ConstraintLayout>
here is the main activity code
public class filter extends AppCompatActivity {
int previewh,previeww;
CameraView cv;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.filter);
cv = findViewById(R.id.cvv);
cv.setLifecycleOwner(this);
cv.start();
final OverlayView ov = findViewById(R.id.overlayView);
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
FirebaseVisionFaceDetectorOptions op =new FirebaseVisionFaceDetectorOptions.Builder()
.setContourMode(FirebaseVisionFaceDetectorOptions.ALL_CONTOURS)
.build();
final FirebaseVisionFaceDetector detector= FirebaseVision.getInstance().getVisionFaceDetector(op);
cv.addFrameProcessor(new FrameProcessor() {
#Override
public void process(#NonNull Frame frame) {
if(frame.getSize() != null)
{
int rotation = frame.getRotation()/ 90;
if(rotation/2 == 0)
{
previewh = cv.getPreviewSize().getHeight();
previeww = cv.getPreviewSize().getWidth();
//Log.d("texts", "process: "+cv.getPreviewSize().getWidth()+" "+cv.getPreviewSize().getHeight());
}else
{
previewh = cv.getPreviewSize().getWidth();
previeww = cv.getPreviewSize().getHeight();
//Log.d("texts", "process: "+cv.getPreviewSize().getWidth()+" "+cv.getPreviewSize().getHeight());
}
FirebaseVisionImageMetadata metadata = new FirebaseVisionImageMetadata.Builder()
.setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21)
.setWidth(frame.getSize().getWidth())
.setHeight(frame.getSize().getHeight())
.setRotation(rotation)
.build();
FirebaseVisionImage fvi = FirebaseVisionImage.fromByteArray(frame.getData(),metadata);
final FirebaseVisionFace[] fc = new FirebaseVisionFace[1];
detector.detectInImage(fvi).addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionFace>>() {
#Override
public void onSuccess(List<FirebaseVisionFace> firebaseVisionFaces) {
for(FirebaseVisionFace f : firebaseVisionFaces)
{
ov.previewh = previewh;
ov.previeww = previeww;
ov.face = f;
ov.invalidate();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
}
});
}
#Override
protected void onResume() {
super.onResume();
cv.start();
}
#Override
protected void onPause() {
super.onPause();
cv.stop();
}
#Override
protected void onDestroy() {
super.onDestroy();
cv.destroy();
}
}
this is the overlay code
public class OverlayView extends View {
public int previewh;
public int previeww;
public FirebaseVisionFace face;
public Rect rect;
private float widthScaleFactor = 1.0f;
private float heightScaleFactor = 1.0f;
Context c;
Bitmap draw = BitmapFactory.decodeResource(getResources(),R.drawable.pimg);
public OverlayView(Context context, AttributeSet attr) {
super(context,attr);
this.c = context;
this.postInvalidate();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(face!= null && canvas != null && previewh != 0 && previeww != 0)
{
widthScaleFactor = getWidth()/previeww;
heightScaleFactor = getHeight()/previewh;
float maxx = 0;
float minx = 10000;
float maxy = 0;
float miny = 10000;
List<FirebaseVisionPoint> facce3= face.getContour(FirebaseVisionFaceContour.ALL_POINTS).getPoints();
for(FirebaseVisionPoint f : facce3)
{
Paint p1 = new Paint();
p1.setStyle(Paint.Style.FILL);
p1.setColor(Color.GREEN);
p1.setStrokeWidth(5);
canvas.drawPoint(translateX(f.getX()+50),translateY(f.getY()+50),p1);
}
maxx = translateX(maxx);
minx = translateX(minx);
maxy = translateY(maxy);
miny = translateY(miny);
//Log.d("texts", "onDraw: "+maxx+" "+minx+" "+maxy+" "+miny);
Rect r1 = new Rect(Math.round(maxx),Math.round(miny),Math.round(minx),Math.round(maxy));
}
}
private float translateX(Float x) {
return getWidth()-scaleX(x);
}
private float scaleX(Float x) {
return x*widthScaleFactor;
}
private float translateY(Float x) {
Resources resources = c.getResources();
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
return (scaleY(x)+resources.getDimensionPixelSize(resourceId));
}
private float scaleY(Float x) { return x*heightScaleFactor; }
}
i have tried adjusting the X and Y values by adding some values to it but in the it turned out that one of the side is being not covered by the points then
what can be done to make it properly aligned on all the sides.
You can check the GraphicOverlay.java on the official firebase/quickstart-android's repository:
/**
* Adjusts the x coordinate from the preview's coordinate system to the view coordinate system.
*/
public float translateX(float x) {
if (overlay.facing == CameraSource.CAMERA_FACING_FRONT) {
return overlay.getWidth() - scaleX(x);
} else {
return scaleX(x);
}
}
/**
* Adjusts the y coordinate from the preview's coordinate system to the view coordinate system.
*/
public float translateY(float y) {
return scaleY(y);
}
Also, you can see the official documentation about face recognition: Detect Faces with MK Kit on Android.

Xamarin load image with loading progressbar upload

how can change this link code to Xamarin
or find another way to load an image with loading progress in Xamarin
I solved It
pic
public class MhnImgview:ImageView{public string Url;
private Context _context;
int mDuration;
int mProgress;
Paint mPaint = new Paint();
RectF mRectF = new RectF();
Color mBackgroundColor;
Color mPrimaryColor;
float mStrokeWidth;
public IOnProgressChangeListener MOnChangeListener; public interface IOnProgressChangeListener
{
void OnChange(int duration, int progress, float rate);
}
public void SetOnProgressChangeListener(IOnProgressChangeListener l)
{
MOnChangeListener = l;
}
protected MhnImgview(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
public MhnImgview(Context context) : base(context)
{
}
public void SetMax(int max)
{
if (max < 0)
{
max = 0;
}
mDuration = max;
}
public int GetMax()
{
return mDuration;
}
public void SetProgress(int progress)
{
if (progress > mDuration)
{
progress = mDuration;
}
mProgress = progress;
MOnChangeListener?.OnChange(mDuration, progress, GetRateOfProgress());
Invalidate();
}
public int GetProgress()
{
return mProgress;
}
public void SetBackgroundColr(Color color)
{
mBackgroundColor = color;
}
public void SetPrimaryColor(Color color)
{
mPrimaryColor = color;
}
float GetRateOfProgress()
{
return (float)mProgress / mDuration;
}
public void SetCircleWidth(float width)
{
mStrokeWidth = width;
}
public async Task ShowImage()
{
var d = await GetImageBitmapFromUrl(Url);
SetImageBitmap(d);
}
protected override void OnDraw(Canvas canvas)
{
base.OnDraw(canvas);
int halfWidth = Width / 2;
int halfHeight = Height / 2;
int radius = halfWidth < halfHeight ? halfWidth : halfHeight;
radius = radius / 2;
float halfStrokeWidth = mStrokeWidth / 2;
mPaint.Color = mBackgroundColor;
mPaint.Dither = true;
mPaint.Flags = PaintFlags.AntiAlias;
mPaint.AntiAlias = true;
mPaint.StrokeWidth = mStrokeWidth;
mPaint.SetStyle(Paint.Style.Stroke);
canvas.DrawCircle(halfWidth, halfHeight, radius - halfStrokeWidth, mPaint);
mPaint.Color = mPrimaryColor;
mRectF.Top = halfHeight - radius + halfStrokeWidth;
mRectF.Bottom = halfHeight + radius - halfStrokeWidth;
mRectF.Left = halfWidth - radius + halfStrokeWidth;
mRectF.Right = halfWidth + radius - halfStrokeWidth;
canvas.DrawArc(mRectF, -90, GetRateOfProgress() * 360, false, mPaint);
canvas.Save();
}
private async Task<Bitmap> GetImageBitmapFromUrl(string imagename)
{
Bitmap imageBitmap = null;
var baseurl = imagename;
try
{
var url = baseurl;
using (var webClient = new WebClient())
{
webClient.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
webClient.DownloadProgressChanged += WebClient_DownloadProgressChanged;
var imageBytes = await webClient.DownloadDataTaskAsync(url);
if (imageBytes != null && imageBytes.Length > 0)
{
imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}
return imageBitmap;
}
catch (Exception ex)
{
var d = ex.Message;
}
return null;
}
private void WebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
SetMax(100);
SetBackgroundColr(Color.Rgb(44,59,76));
SetPrimaryColor(Color.Rgb(236,104,88));
SetCircleWidth(7.5f);
SetProgress(e.ProgressPercentage);
}
public MhnImgview(Context context, IAttributeSet attrs) : base(context, attrs)
{
}
public MhnImgview(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr)
{
}
public MhnImgview(Context context, IAttributeSet attrs, int defStyleAttr, int defStyleRes) : base(context, attrs, defStyleAttr, defStyleRes)
{
}
}
for use it
var img = FindViewById<MhnImgview>(Resource.Id.imgmhn);
img.Url = "http://www.neyrizcement.com/upload/3rcqesmc.jpg";
await img.ShowImage();

Image Does Not Animate and is Stuck in one Frame

I'm having a problem in my code where the animation from another class does not animate and is stuck in one frame. The image moves across the screen in the right manner though. I know that the problem is somehow related to the UPDATE method of the animation. I have tried every possible solutions in my knowledge to find what causes the error and the solutions I found online were not quite helpful. Any help will be appreciated.
Here's my Code:
LevelOneScreen.java
public class LevelOneScreen implements Screen {
private final MyGame app;
WalkAnimate walkAnimate;
private Stage stage;
private Image levelOneImage;
private Image holdStartImage;
public Image walkRightImage;
public Image walkLeftImage;
public float deltaTime = Gdx.graphics.getDeltaTime();
public LevelOneScreen(final ThumbChase app){
this.app = app;
this.stage = new Stage(new StretchViewport(app.screenWidth,app.screenHeight , app.camera));
}
#Override
public void show() {
Gdx.input.setInputProcessor(stage);
walkAnimate = new WalkAnimate();
walkAnimate.update(deltaTime);
levelOneBackground();
holdStart();
ninjaWalk();
}
public void holdStart(){
Texture holdStartTexture = new Texture("HoldStart.png");
holdStartImage = new Image(holdStartTexture);
float holdStartImageW = holdStartImage.getWidth();
float holdStartImageH = holdStartImage.getHeight();
float holdStartImgWidth = app.screenWidth*0.8f;
float holdStartImgHeight = holdStartImgWidth *(holdStartImageH/holdStartImageW);
holdStartImage.isTouchable();
holdStartImage.setSize(holdStartImgWidth,holdStartImgHeight);
holdStartImage.setPosition(stage.getWidth()/2-holdStartImgWidth/2,stage.getHeight()/2-holdStartImgHeight/2);
stage.addActor(holdStartImage);
holdStartImage.addListener(new ActorGestureListener(){
/* public void touchDown (InputEvent event, float x, float y, int pointer, int button){
holdStartImage.setVisible(false);
};*/
public void fling(InputEvent event, float velocityX, float velocityY, int button) {
holdStartImage.setVisible(false);
}
public void touchDown (InputEvent event, float x, float y, int pointer, int button){
holdStartImage.setVisible(false);
};
public void touchDrag (InputEvent event, float x, float y, int pointer, int button){
holdStartImage.setVisible(false);
};
});
}
public void levelOneBackground(){
Texture levelOneTexture = new Texture("BGBlue Resize.png");
levelOneImage = new Image(levelOneTexture);
levelOneImage.setSize(app.screenWidth,app.screenHeight);
levelOneImage.setPosition(0,0);
stage.addActor(levelOneImage);
/*levelOneImage.addListener(new ActorGestureListener(){
public void touchDown (InputEvent event, float x, float y, int pointer, int button){
holdStartImage.setVisible(false);
};
});*/
}
public void ninjaWalk(){
TextureRegion ninjaWalkRight = new TextureRegion(walkAnimate.getCurrentFrameRight());
TextureRegion ninjaWalkLeft = new TextureRegion(walkAnimate.getCurrentFrameLeft());
//Texture ninjaWalkRight = new Texture("badlogic.jpg");
//Texture ninjaWalkLeft = new Texture("badlogic.jpg");
walkRightImage = new Image(ninjaWalkRight);
walkLeftImage = new Image(ninjaWalkLeft);
float walkImageW = walkRightImage.getWidth();
float walkImageH = walkRightImage.getHeight();
float walkImageWidth = app.screenWidth*0.25f;
float walkImageHeight = walkImageWidth*(walkImageH/walkImageW);
walkRightImage.isTouchable();
walkLeftImage.isTouchable();
walkRightImage.setSize(walkImageWidth,walkImageHeight);
walkLeftImage.setSize(walkImageWidth,walkImageHeight);
walkRightImage.setPosition(stage.getWidth()/2-walkImageWidth/2,0);
walkLeftImage.setPosition(stage.getWidth()/2-walkImageWidth/2,0);
walkRightImage.addAction(moveBy(app.screenWidth*0.2f,0,1f));
stage.addActor(walkRightImage);
walkRightImage.addListener(new ActorGestureListener(){
public void pan(InputEvent event, float x, float y, float deltaX, float deltaY) {
holdStartImage.setVisible(true);
}
});
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//walkAnimate.update(deltaTime);
update(delta);
}
public void update(float deltaTime){
stage.act(deltaTime);
stage.draw();
app.batch.begin();
app.batch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
stage.dispose();
}
}
WalkAnimate.java
public class WalkAnimate {
public MyGame app;
public Stage stage;
private Animation walkAnimationRight;
private Animation walkAnimationLeft;
private Texture walkSheetRight;
private Texture walkSheetLeft;
private TextureRegion[] walkFramesRight;
private TextureRegion[] walkFramesLeft;
private TextureRegion currentFrameRight;
private TextureRegion currentFrameLeft;
private float stateTime;
private Rectangle bound; //used for positioning and collision detection
private static final int FRAME_COLS_WALK = 3;
private static final int FRAME_ROWS_WALK= 2;
private float screenWidth = Gdx.graphics.getWidth();
private float screenHeight = Gdx.graphics.getHeight();
public float currentFrameWidth = (float)(screenHeight*0.15);
public float currentFrameHeight = (float)(screenHeight*0.15);
public float walkSheetWidth;
public float walkSheetHeight;
public WalkAnimate () {
walkSheetRight = new Texture("ninjaWalkRight.png");
walkSheetWidth = walkSheetRight.getWidth();
walkSheetHeight = walkSheetRight.getWidth();
TextureRegion[][] tmp = TextureRegion.split(walkSheetRight, (int) walkSheetRight.getWidth() / FRAME_COLS_WALK, (int) walkSheetRight.getHeight() / FRAME_ROWS_WALK);
walkFramesRight = new TextureRegion[FRAME_COLS_WALK * FRAME_ROWS_WALK];
int index = 0 ;
for (int i = 0; i < FRAME_ROWS_WALK; i++) {
for (int j = 0; j < FRAME_COLS_WALK; j++) {
walkFramesRight[index++] = tmp[i][j];
}
}
walkAnimationRight = new Animation(0.044f, walkFramesRight);
stateTime = 0f;
walkSheetLeft = new Texture("ninjaWalkLeft.png");
walkSheetWidth = walkSheetLeft.getWidth();
walkSheetHeight = walkSheetLeft.getWidth();
TextureRegion[][] tmp1 = TextureRegion.split(walkSheetLeft, (int) walkSheetRight.getWidth() / FRAME_COLS_WALK, (int)walkSheetLeft.getHeight() / FRAME_ROWS_WALK);
walkFramesLeft = new TextureRegion[FRAME_COLS_WALK * FRAME_ROWS_WALK];
int index1 = 0;
for (int i = 0; i < FRAME_ROWS_WALK; i++) {
for (int j = 0; j < FRAME_COLS_WALK; j++) {
walkFramesLeft[index1++] = tmp1 [i][j];
}
}
walkAnimationLeft = new Animation(0.044f, walkFramesLeft);
stateTime = 0f;
currentFrameRight = walkAnimationRight.getKeyFrame(stateTime, true);
currentFrameLeft = walkAnimationLeft.getKeyFrame(stateTime, true);
}
public Rectangle getBound(){
return bound;
}
public void update(float delta){
stateTime += delta;
}
public TextureRegion getCurrentFrameRight(){
return currentFrameRight;
}
public TextureRegion getCurrentFrameLeft(){
return currentFrameLeft;
}
}
Like the earlier comment by Eames. Just by glancing at your code, I can say that you should begin by moving
walkAnimate.update(delta);
To the render section. The show section only runs once (when the class is started). Your walkAnimate.update(delta) should be running constantly to change the frame when is time. Otherwise it would only update once.
You can also do it the way I do it.
The class where you are going to use it. The 16 represents the number of images. The 1F means it is done in one second.
public void show() {
texture = new Texture("item/coin_animation.png");
animation = new Animation(new TextureRegion(texture), 16, 1f);
}
public void render(float delta) {
animation.update(delta);
}
Animation Class
public Array<TextureRegion> frames;
private float maxFrameTime;
private float currentFrameTime;
private int frameCount;
private int frame;
private static TextureRegion textureRegion;
public Animation(TextureRegion region, int frameCount, float cycleTime){
textureRegion = region;
frames = new Array<TextureRegion>();
int frameWidth = textureRegion.getRegionWidth() / frameCount;
for (int i = 0; i < frameCount; i++){
frames.add(new TextureRegion(textureRegion, i * frameWidth, 0, frameWidth, textureRegion.getRegionHeight()));
}
this.frameCount = frameCount;
maxFrameTime = cycleTime / frameCount;
frame = 0;
}
public void update(float delta){
currentFrameTime += delta;
if (currentFrameTime > maxFrameTime){
frame++;
currentFrameTime = 0;
}
if (frame >= frameCount)
frame = 0;
}
public TextureRegion getFrame(){
return frames.get(frame);
}
public void restart(){
frame = 0;
currentFrameTime = 0;
}
I will answer my question, I've tried using a separate stage for the animation and it works. I also used inputmultiplexor to set two stages both as inputprocessors. I know that this is not the best solution and I am open for more proper solutions. This is open for editing.

onItemClick with toast content of an array list

What I need is a toast or something like that with content of an array list, that opens when I click on a LinearLayout item. But I don't know how to implement it with the holder view.
public class CanteenListAdapter extends BaseAdapter implements AdapterView.OnItemClickListener {
private ArrayList<CanteenMenu> listData;
private LayoutInflater layoutInflater;
private Context context;
public CanteenListAdapter(ArrayList<CanteenMenu> listData, Context bContext){
this.listData = listData;
layoutInflater = LayoutInflater.from(bContext);
this.context = bContext;
Collections.sort(this.listData);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View cView, ViewGroup parent) {
ViewHolder holder;
if(cView==null){
cView = layoutInflater.inflate(R.layout.activity_canteen_tab_listitem, null);
holder = new ViewHolder();
holder.date = (TextView) cView.findViewById(R.id.canteen_header);
holder.ll = (LinearLayout) cView.findViewById(R.id.canteen_linearLayout);
int j = 0;
for (int i = 0; i < listData.get(position).getCategory().length; i++) {
TextView description = new TextView(context);
TextView category = new TextView(context);
description.setText(listData.get(position).getName()[i]);
category.setText(listData.get(position).getCategory()[i]);
holder.ll.addView(category, j);
holder.ll.addView(description,j + 1);
j += 2;
}
cView.setTag(holder);
} else{
holder = (ViewHolder) cView.getTag();
}
int j = 0;
for(int i = 0; i < listData.get(position).getCategory().length; i++) {
if(holder.ll.getChildAt(j) != null) {
((TextView) holder.ll.getChildAt(j)).setText(listData.get(position).getCategory()[i]);
((TextView) holder.ll.getChildAt(j + 1)).setText(listData.get(position).getName()[i]);
}
j += 2;
}
return cView;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
static class ViewHolder {
LinearLayout ll;
TextView date;
TextView name;
TextView category;
}
}
Can anyone help ?

JPanel animation

Hy there.
I am trying to make a JPanel which reacts to certain events and plays a little animation. For example if I click on a button, it should flash red.(I need this to indicate when a file was successfully saved(green flash), or a error occurred(red flash).
I found some tutorials on animations, but I'm having a hard time changing it to fit my needs. For example most of the tutorials instantiate a Timer at the beginning. But I only need the timer to be active for that short amount of time where the flash is played and than stop. Also I need different animation types.(red flash, green flash...)
This is what I have got so far, which is basically nothing:
package MainPackage;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class StatusBar extends JPanel implements ActionListener{
Timer t = new Timer(10, this);
boolean stop = false;
Color color;
public void paintComponent (Graphics g) {
super.paintComponent(g);
setBackground(color);
}
public void confirm(){
color = new Color(46, 204, 113);
t.start();
}
public void warning(){
color = Color.red;
t.start();
}
#Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
Thanks in advance!
public class flashclass extends JFrame{
Thread th;
Color defaultColor, flashColor;
int i;
boolean success;
JPanel p;
public flashclass(){
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
success = false;
defaultColor = new Color(214,217,223);
p = new JPanel();
JButton rbtn = new JButton("Red flash");
JButton gbtn = new JButton("Green flash");
rbtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
success = false;
flash(success);
}
});
gbtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
success = true;
flash(success);
}
});
p.add(rbtn);
p.add(gbtn);
getContentPane().add(p);
}
public void flash(boolean success){
i=0;
if(!success){
flashColor = Color.red;
}
else{
flashColor = Color.green;
}
th = new Thread(new Runnable() {
#Override
public void run() {
while(i<10){
p.setBackground(flashColor);
i++;
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
p.setBackground(defaultColor);
}
}
});
th.start();
}
}
public static void main(String args[]){
new flashclass();
}
}
So here is the finished class:
New animations can be added easily. And they also do not interfere with each other. So multiple states can be triggered simultaneously.
The StatusBar.java
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JComponent;
import javax.swing.Timer;
public class StatusBar extends JComponent implements ActionListener{
int width;
int height;
boolean bLoad, bWarn, bConfirm, bError;
Timer timer;
Color bgColor;
int xPosLoad, alphaWarn, alphaConfirm, alphaError;
float cntWarn, cntConfirm, cntError;
int cntLoad;
final int barLength = 200;
public StatusBar(Color bg){
width = getWidth();
height = getHeight();
xPosLoad = -barLength;
alphaWarn = 0;
alphaConfirm = 0;
alphaError = 0;
bgColor = bg;
timer = new Timer(10, this);
this.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent event) {
width = getWidth();
height = getHeight();
}
});
}
#Override
protected void paintComponent(Graphics g) {
// Background
g.setColor(bgColor);
g.fillRect(0, 0, width, height);
// loading
Graphics2D g2d = (Graphics2D)g;
GradientPaint gp = new GradientPaint(xPosLoad,0, new Color(0,0,0,0), xPosLoad+barLength, 0, new Color(200, 200, 255));
g2d.setPaint(gp);
g2d.fillRect(xPosLoad, 0, barLength, height);
// Green
g.setColor(new Color(20, 210, 60, alphaConfirm));
g.fillRect(0, 0, width, height);
// Yellow
g.setColor(new Color(255, 223, 0, alphaWarn));
g.fillRect(0, 0, width, height);
// Red
g.setColor(new Color(255, 0, 0, alphaError));
g.fillRect(0, 0, width, height);
}
#Override
public void actionPerformed(ActionEvent e) {
// step increase for all active components
boolean toggle = false;
if (bConfirm){
if(cntConfirm < 1){
cntConfirm += 0.01f;
alphaConfirm = lerp(cntConfirm, 255, true);
}else{
bConfirm = false;
cntConfirm = 0;
alphaConfirm = 0;
}
toggle = true;
}
if (bWarn){
if(cntWarn < 1){
cntWarn += 0.01f;
alphaWarn = lerp(cntWarn, 255, true);
}else{
bWarn = false;
cntWarn = 0;
alphaWarn = 0;
}
toggle = true;
}
if (bError){
if(cntError < 1){
cntError += 0.01f;
alphaError = lerp(cntError, 255, true);
}else{
bError = false;
cntError = 0;
alphaError = 0;
}
toggle = true;
}
if (bLoad){
if(cntLoad < 100){
cntLoad += 1;
xPosLoad = (cntLoad * (width + barLength)) / 100 - barLength;
}else{
cntLoad = 0;
xPosLoad = -barLength;
}
toggle = true;
}
repaint();
if (!toggle){
timer.stop();
}
}
private void startTimer(){
if (!timer.isRunning())
timer.start();
}
public void setBG(Color bg){
bgColor = bg;
System.out.println("Color: " + bgColor);
repaint();
}
// Green flash
public void confirm(){
// set values
bConfirm = true;
alphaConfirm = 255;
cntConfirm = 0;
startTimer();
}
//Yellow flash
public void warning(){
// restart values
bWarn = true;
alphaWarn = 255;
cntWarn = 0;
startTimer();
}
//Red Flash
public void error(){
// restart values
bError = true;
alphaError = 255;
cntError = 0;
startTimer();
}
//Blue load
public void loadStart(){
// restart values
bLoad = true;
xPosLoad = -barLength;
cntLoad = 0;
startTimer();
}
public void loadEnd(){
bLoad = false;
xPosLoad = -barLength;
}
private int lerp(float progress, int max, boolean inverse){
float x = progress;
float x2 = (float) Math.pow(x, 4);
float g = x + (1 - x);
float y = (float) ((float) x2 / (float)(Math.pow(g, 4)));
y = Math.min(y, 1);
y = Math.max(y, 0);
int res = (int) (y * max);
if (inverse){
res = max - res;
}
return res;
}
}
And the Example.java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Example extends JFrame{
public static void main(String[] args){
new Example("Stat Example");
}
public Example(String title){
super(title);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
StatusBar stat = new StatusBar(Color.black);
stat.setPreferredSize(new Dimension(0, 10));
JPanel panel = new JPanel();
JButton bConfirm = new JButton("Confirm");
JButton bWarn = new JButton("Warning");
JButton bErr = new JButton("Error");
JButton bLoadS = new JButton("Start Loading");
JButton bLoadE = new JButton("End Loading");
panel.add(bConfirm);
panel.add(bWarn);
panel.add(bErr);
panel.add(bLoadS);
panel.add(bLoadE);
this.getContentPane().add(stat, BorderLayout.CENTER);
this.getContentPane().add(panel, BorderLayout.SOUTH);
this.pack();
this.setVisible(true);
// Listener
bConfirm.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
stat.confirm();
}
});
bWarn.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
stat.warning();
}
});
bErr.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
stat.error();
}
});
bLoadS.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
stat.loadStart();
}
});
bLoadE.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
stat.loadEnd();
}
});
}
}

Resources