Graphics>AnimateDrawables
这里上将一个drawable会知道一个自定义的view上面的
自定一个view,设置在setcontentview上,但是如果用代码创建view的话,没有指定尺寸的话是适配父窗体可用尺寸的。不做任何处理就是全屏显示的。
下面的代码做默认尺寸处理700*1000的,这个view在画出来之前要测量尺寸。还有另一种方法,在xml文件中设置尺寸。这两种方式都是可以的。
在构造方法中加载一张图片成drawable
public class AnimateDrawables extends GraphicsActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SampleView sampleView = new SampleView(this);
setContentView(sampleView);
}
private static class SampleView extends View {
private AnimateDrawable mDrawable;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(720,1000);//设置测量尺寸
}
public SampleView(Context context) {
super(context);
setFocusable(true);
setFocusableInTouchMode(true);
Drawable dr = context.getResources().getDrawable(R.drawable.beach);
dr.setBounds(0, 0, dr.getIntrinsicWidth(), dr.getIntrinsicHeight());//设置位置
Animation an = new TranslateAnimation(0, 100, 0, 200);
an.setDuration(2000);
an.setRepeatCount(-1);
an.initialize(10, 10, 10, 10);
mDrawable = new AnimateDrawable(dr, an);
an.startNow();
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.GREEN);
mDrawable.draw(canvas);
invalidate();
}
}
}
根据当前动画计算的矩阵,实际改变画布矩阵实现动画效果。
public class AnimateDrawable extends ProxyDrawable {
private Animation mAnimation;
private Transformation mTransformation = new Transformation();
public AnimateDrawable(Drawable target) {
super(target);
}
public AnimateDrawable(Drawable target, Animation animation) {
super(target);
mAnimation = animation;
}
public Animation getAnimation() {
return mAnimation;
}
public void setAnimation(Animation anim) {
mAnimation = anim;
}
public boolean hasStarted() {
return mAnimation != null && mAnimation.hasStarted();
}
public boolean hasEnded() {
return mAnimation == null || mAnimation.hasEnded();
}
@Override
public void draw(Canvas canvas) {
Drawable dr = getProxy();
if (dr != null) {
int sc = canvas.save();
Animation anim = mAnimation;
if (anim != null) {
//设置anim的动画的矩阵信息到mTransformation中
anim.getTransformation(AnimationUtils.currentAnimationTimeMillis(), mTransformation);
canvas.concat(mTransformation.getMatrix());//当前矩阵设置到画布,改变画布矩阵
}
dr.draw(canvas);
canvas.restoreToCount(sc);
}
}
}