I'm a beginner at this, so bear with me.
I have a bitmap image, and I want to animate it programmatically.
I want to have the animation of the logo in the video "Indie Nation"
https://www.youtube.com/watch?v=yRU2rU2k_NI
Skip to like 0:20 to see.
Anyways, here's what I understand that I have to do. Correct me if I am wrong.
I plan to make an object, have a
public void draw(Canvas canvas)
method that will play around with the bitmap.
Also, do I need to use a Matrix, or is it sufficient to modify the canvas directly?
Thanks in advance!
- Apply scaling for zooming in and out
- Apply transformations for slightly moving it around
Yes, your understanding is correct.
You can use matrix to achieve the expected result as shown below.
public class LogoView extends View {
public LogoView(Context context) {
super(context);
init();
}
public LogoView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public LogoView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
logo = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
logoLeft = -logo.getWidth() >> 1;
logTop = -logo.getHeight() >> 1;
matrix = new Matrix();
}
private Bitmap logo;
private Matrix matrix;
private float logoLeft, logTop;
private float SCALE_FACTOR = 0.07f;
private float TRANSLATE_FACTOR = 0.03f;
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
matrix.reset();
matrix.setTranslate(getWidth() >> 1, getHeight() >> 1);
canvas.setMatrix(matrix);
float scaleFactor = (float) (Math.random() * SCALE_FACTOR) + 1.f;
canvas.scale(scaleFactor, scaleFactor);
float dx = (float) ((Math.random() - 0.5) * TRANSLATE_FACTOR) * logo.getWidth();
float dy = (float) ((Math.random() - 0.5) * TRANSLATE_FACTOR) * logo.getHeight();
canvas.translate(dx, dy);
canvas.drawBitmap(logo, logoLeft, logTop, null);
postInvalidateDelayed(150);
}
}