How to make animation when I use canvas - android

For example: myPos.getCoordX() is 0 and myPos.getCoordY() is 0
When I update the variable, myPos.getCoordX() is 50 and myPos.getCoordY() is 100
Then I call the showPosition() method again.
I want to: start a moving animation from 0,0 to 50,100
private void showPosition() {
Bitmap floorPlan = BitmapFactory.decodeResource(getResources(),
R.drawable.wallpaper).copy(Bitmap.Config.ARGB_4444, true);
Bitmap point = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher).copy(Bitmap.Config.ARGB_4444, true);
Bitmap PositionOnFloorplan = overlay(floorPlan, point);
// 1
PositionOnFloorplan = floorPlan.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(PositionOnFloorplan);
canvas.drawBitmap(point, (float) (myPos.getCoordX()),
(float) (myPos.getCoordY()), null);
ImageView imageView = (ImageView) findViewById(R.id.imggg);
imageView.setAdjustViewBounds(true);
imageView.setImageBitmap(PositionOnFloorplan);
}
private Bitmap overlay(Bitmap floorPlan, Bitmap point) {
Bitmap bmOverlay = Bitmap.createBitmap(floorPlan.getWidth(),
floorPlan.getHeight(), floorPlan.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(floorPlan, new Matrix(), null);
canvas.drawBitmap(point, (float) (myPos.getCoordX()),
(float) (myPos.getCoordY()), null);
return bmOverlay;
}

As you aren't using a custom view and the onDraw method to update your canvas, I recommend using a property animator to animate the canvas drawing.
Below is code for an example animation that moves a view in the X with canvas.translate(value,0);. You will need to add in the Y value, example: canvas.translate(valueX,valueY);. Just define another ValueAnimator for the Y, create an AnimatorSet, and do animatorSet.playTogether(valueanimatorX, valueanimatorY) instead, finishing with animatorSet.start();
public void doCanvas(){
//Create our resources
Bitmap bitmap = Bitmap.createBitmap(mLittleChef.getWidth(), mLittleChef.getHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(bitmap);
final Bitmap chefBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.dish_special);
final Bitmap starBitmap= BitmapFactory.decodeResource(getResources(),R.drawable.star);
//Link the canvas to our ImageView
mLittleChef.setImageBitmap(bitmap);
//animate from canvas width, to 0, and back to canvas width
ValueAnimator animation= ValueAnimator.ofInt(canvas.getWidth(),0,canvas.getWidth());
animation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
int value = (Integer) animation.getAnimatedValue();
//Clear the canvas
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
canvas.drawBitmap(chefBitmap, 0, 0, null);
canvas.save();
canvas.translate(value,0);
canvas.drawBitmap(starBitmap, 0, 0, null);
canvas.restore();
//Need to manually call invalidate to redraw the view
mLittleChef.invalidate();
}
});
animation.addListener(new AnimatorListenerAdapter(){
#Override
public void onAnimationEnd(Animator animation) {
simpleLock= false;
}
});
animation.setInterpolator(new LinearInterpolator());
animation.setDuration(mShortAnimationDuration);
animation.start();
}

Related

How to draw on canvas and convert to bitmap?

I'm tring to draw some line and shapes on canvas and then convert it to bitmap on ImageView. I'm usin a custom class that extands "View" and on "OnDraw method i'm drawing the lines. here is my code(this class only draw simple lines) :
public class finalDraw extends View {
public finalDraw(Context context) {
super(context);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.BLUE);
for (int i = 0; i <100; i++) {
canvas.drawLine(xStart * i + 50 , yStart , stopX + 30 , stopY,paint);
}
invalidate();
}
}
How can i get the drawing result and show it on ImageView?
Thanks!
Found this article may help: http://www.informit.com/articles/article.aspx?p=2143148&seqNum=2
draw.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Bitmap imageBitmap = Bitmap.createBitmap(imageView.getWidth(), imageView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(imageBitmap);
float scale = getResources().getDisplayMetrics().density;
Paint p = new Paint();
p.setColor(Color.BLUE);
p.setTextSize(24*scale);
canvas.drawText("Hello", imageView.getWidth()/2, imageView.getHeight()/2, p);
imageView.setImageBitmap(imageBitmap);
}
});
Create a Canvas with a bitmap, by Canvas(Bitmap bitmap). All draws to that canvas will in that bitmap.

the image doesn't fit in canvas android

I draw a bitmap image into a canvas with this code:the bitmap get from user galley
public class CanvasView extends View {
Bitmap canvasBitmap;
Canvas drawCanvas;
public CanvasView(Context context,AttributeSet attrs) {
super(context,attrs);
}
public void setCanvasPath(String bitmap_path) {
BitmapFactory.Options decode_options = new BitmapFactory.Options();
decode_options.inMutable = true;
canvasBitmap = BitmapFactory.decodeFile(bitmap_path,decode_options);
drawCanvas = new Canvas(canvasBitmap);
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (canvasBitmap != null) {
Matrix matrix=new Matrix();
Matrix m = drawCanvas.getMatrix();
RectF drawableRect = new RectF(0, 0, canvasBitmap.getWidth(), canvasBitmap.getHeight());
RectF viewRect = new RectF(0, 0, drawCanvas.getWidth(),drawCanvas.getHeight());
m.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.CENTER);
canvas.drawBitmap(canvasBitmap,m , null);
}
}
}
but when i draw the bitmap it get out of the canvas view,i don't want to stretch the image,i want to my canvas act like image view in android.

Sprite Sheet - new sprite being drawn on top of old sprites

Basically I tried to use a sprite sheet for animation. The aim is to count from 1 to 8 with 1 second interval. The numbers are image on a sprite sheet. The problem is once the number is being drawn to the canvas, it just won't go away. New image just drawn on top of the unwanted old image. Like this:
Is there a way to clear what has been drawn, so that new image can be drawn on a clean canvas?
DrawStripFrame Class:
public class DrawStripFrame extends SurfaceView implements Runnable{
/**variables declared here*/
public DrawStripFrame (Context context){
super (context);
this.context = context;
holder = getHolder();
}
public void setDrawStripFrame(Bitmap bitmap, int width, int height, int columns){
this.bitmap = bitmap;
this.width = width;
this.height = height;
this.columns = columns;
}
}
#Override
public void run(){
while(running){
if(!holder.getSurface().isValid())
continue;
Canvas canvas = holder.lockCanvas();
draw(canvas);
holder.unlockCanvasAndPost(canvas);
}
}
public void draw (Canvas canvas){
update();
/**4 being no. of columns and 2 being no. of row*/
int u = (frame % 4)*(width/4);
int v = (frame / 4)*(height/2);
Rect src = new Rect(u,v,u+(width/4),v+(height/2));
Rect dst = new Rect (0,0, 100,100);
Paint paint = new Paint();
canvas.drawBitmap(bitmap, src, dst, paint);
}
public void resume() {
running = true;
gameloop = new Thread(this);
gameloop.start();
}
public void update (){
frame++;
if (frame>10)
frame = 0;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
In your case you could just redraw the canvas with a color like this:
public void draw (Canvas canvas){
update();
// clearing canvas
canvas.drawColor(Color.BLUE); // whatever color you need it to be
/**4 being no. of columns and 2 being no. of row*/
int u = (frame % 4)*(width/4);
int v = (frame / 4)*(height/2);
Rect src = new Rect(u,v,u+(width/4),v+(height/2));
Rect dst = new Rect (0,0, 100,100);
Paint paint = new Paint();
canvas.drawBitmap(bitmap, src, dst, paint);
}

TranslateAnimation like a curve way in android

How can I create animation for moving a image like a curve from top to bottom? Here I used TranslateAnimation for this,
But it will move the image from top to bottom depends on the x, y co-ordinates. But, I want to move the image like a curve.
But in my code, it moves like a line.
public class ImageMoveActivity extends Activity {
/** Called when the activity is first created. */
TranslateAnimation transform;
TextView tv;
ImageView im1,im2,im3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
transform = new TranslateAnimation(0, 150, 0, 300);
//transform = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 1, Animation.RELATIVE_TO_PARENT, 20, Animation.RELATIVE_TO_PARENT, 50, Animation.RELATIVE_TO_PARENT, 0);
//im1 = (ImageView)findViewById(R.id.imageView1);
im1 = (ImageView)findViewById(R.id.imageView1);
im2 = (ImageView)findViewById(R.id.imageView2);
im3 = (ImageView)findViewById(R.id.imageView3);
tv = (TextView)findViewById(R.id.Textview);
Bitmap bitmap = BitmapFactory.decodeResource(this
.getResources(), R.drawable.xxl);
/* set other image top of the first icon */
Bitmap bitmapStar = BitmapFactory.decodeResource(this
.getResources(), R.drawable.icon);
Bitmap bmOverlay = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
// Bitmap bmOverlay1 = Bitmap.createBitmap(bitmapStar.getWidth(),
// bitmapStar.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bmOverlay);
//Canvas canvas1 = new Canvas(bmOverlay1);
canvas.drawARGB(0x00, 0, 0, 0);
canvas.drawBitmap(bitmap, 0, 0, null);
//canvas1.drawARGB(0x00, 0, 0, 0);
canvas.drawBitmap(bitmapStar, 0, 0, null);
BitmapDrawable dr = new BitmapDrawable(bmOverlay);
//BitmapDrawable dr1 = new BitmapDrawable(bmOverlay1);
dr.setBounds(10, 30, 10, 30);
//dr1.setBounds(10, 30, 10, 30);
im1.setImageDrawable(dr);
//im3.setImageDrawable(dr1);
//im1.setImageDrawable(R.drawable.xxl);
im1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
start();
hide();
}
private void start() {
// TODO Auto-generated method stub
im1.startAnimation(transform);
transform.setDuration(1000);
//transform.setFillAfter(true);
}
private void hide() {
// TODO Auto-generated method stub
im1.setVisibility(View.GONE);
}
});
}
}
Can any one help me on this?
TranslateAnimation can move Views from one point to another in a straight line. As far as I know you can't give any other path to it. Try using custom views and canvas for the the this, where you can pass x and y coordinates while drawing and invalidating the view. You need to override the following method while extending the View class. The changeCoordinate() method here can change the x,y coordinates in a curve.
public void onDraw(Canvas canvas){
canvas.drawBitmap(bitmap,x,y,null);
changeCoordinate();
invalidate()
}
You can create a series of translate animation from one point to another on curve and apply the animation to views.
Like if we have an imageView which is to be animated, and a1, and a2 are animations to be applied:
imgView.clearAnimation();
imgView.startAnimation(a1);
imgView.clearAnimation();
imgView.startAnimation(a2);

How to rotate the image without changing its size?

I am developing an android app where I have to rotate a circular image around another circular image, but when I am running this the size of my circular image gets automatically changing continuously. So please help me how to solve this. Here is my code
public class JobSearch extends Activity implements OnTouchListener {
private ImageView dialer;
private float y=0;
public boolean onTouch(View v, MotionEvent event) {
double r=Math.atan2(event.getX()-dialer.getWidth()/2, dialer.getHeight()/2-event.getY());
int rotation=(int)Math.toDegrees(r);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
//x=event.getX();
y=event.getY();
updateRotation(rotation);
break;
case MotionEvent.ACTION_UP:
break;
}//switch
return true;
}//onTouch
private void updateRotation(double rot){
float newRot=new Float(rot);
Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.round_button_big);
Matrix matrix=new Matrix();
matrix.postRotate(newRot);//,bitmap.getWidth()/2,bitmap.getHeight()/2);
Bitmap reDrawnBitmap=Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
dialer.setImageBitmap(reDrawnBitmap);
if(newRot>=-5 && newRot<=5)
Toast.makeText(this,"12 O\'Clock",Toast.LENGTH_SHORT).show();
if(newRot>=85 && newRot<=95)
Toast.makeText(this,"3 O\'Clock",Toast.LENGTH_SHORT).show();
if(newRot>=175 || newRot<=-175)
Toast.makeText(this,"6 O\'Clock",Toast.LENGTH_SHORT).show();
if(newRot>=-95 && newRot<=-85)
Toast.makeText(this,"9 O\'Clock",Toast.LENGTH_SHORT).show();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dialer = (ImageView) findViewById(R.id.big_button);
dialer.setOnTouchListener(this);
}//onCreate
}
This this one; worked for me perfectly.
private Bitmap rotateBitmap(Bitmap bitmap, int rotationAngleDegree){
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int newW=w, newH=h;
if (rotationAngleDegree==90 || rotationAngleDegree==270){
newW = h;
newH = w;
}
Bitmap rotatedBitmap = Bitmap.createBitmap(newW,newH, bitmap.getConfig());
Canvas canvas = new Canvas(rotatedBitmap);
Rect rect = new Rect(0,0,newW, newH);
Matrix matrix = new Matrix();
float px = rect.exactCenterX();
float py = rect.exactCenterY();
matrix.postTranslate(-bitmap.getWidth()/2, -bitmap.getHeight()/2);
matrix.postRotate(rotationAngleDegree);
matrix.postTranslate(px, py);
canvas.drawBitmap(bitmap, matrix, new Paint( Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG ));
matrix.reset();
return rotatedBitmap;
}
Try this code for Rotating Image -
public class bitmaptest extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout linLayout = new LinearLayout(this);
// load the origial BitMap (500 x 500 px)
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.android);
int width = bitmapOrg.width();
int height = bitmapOrg.height();
int newWidth = 200;
int newHeight = 200;
// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// rotate the Bitmap
matrix.postRotate(45);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
width, height, matrix, true);
// make a Drawable from Bitmap to allow to set the BitMap
// to the ImageView, ImageButton or what ever
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
ImageView imageView = new ImageView(this);
// set the Drawable on the ImageView
imageView.setImageDrawable(bmd);
// center the Image
imageView.setScaleType(ScaleType.CENTER);
// add ImageView to the Layout
linLayout.addView(imageView,
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT
)
);
// set LinearLayout as ContentView
setContentView(linLayout);
}
}
And, also see this Tutorial
This is my code to rotate image around itself and slowly reduce the speed
rotateAnimation1 = new RotateAnimation(0, 360,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
rotateAnimation1.setInterpolator(new LinearInterpolator());
rotateAnimation1.setDuration(duration);
rotateAnimation1.setRepeatCount(0);
imgBottle.startAnimation(rotateAnimation1);
flagSpinAvailable = false;
rotateAnimation1.setAnimationListener(new AnimationListener() {
public void onAnimationStart(Animation anim) {
};
public void onAnimationRepeat(Animation anim) {
};
public void onAnimationEnd(Animation anim) {
duration = duration + 70;
startMoving();
};
});
this is the code of rotate the image
Bitmap bMap = BitmapFactory.decodeResource(getResources(),R.drawable.test);
Matrix mat = new Matrix();
mat.postRotate(90);
Bitmap bMapRotate = Bitmap.createBitmap(bMap, 0, 0,
bMap.getWidth(), bMap.getHeight(), mat, true);
BitmapDrawable bmd = new BitmapDrawable(bMapRotate);
image.setImageBitmap(bMapRotate);
image.setImageDrawable(bmd);

Categories

Resources