代码前的两件事:
- 你根本不能使用imageview?因为您可以将其链接到画布并使用位图,但它仍然是图像视图。
- 我相信您遇到的主要问题是另一个答案是没有为其设置动画,并且您错过了调用 invalidate() 视图并将其重绘为旋转的调用。
所以有两种方法:
第一个是imageview,我个人认为它更容易更好。下面是我的活动类中的一个方法,mLittleChef 是一个 ImageView。
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);
//Link the canvas to our ImageView
mLittleChef.setImageBitmap(bitmap);
ValueAnimator animation= ValueAnimator.ofFloat(0, 359, 129, 186);
animation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = (Float) animation.getAnimatedValue();
//Clear the canvas
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
canvas.save();
canvas.rotate(value, canvas.getWidth()/2, canvas.getHeight()/2);
canvas.drawBitmap(chefBitmap, 0, 0, null);
canvas.restore();
mLittleChef.invalidate();
}
});
animation.setInterpolator(new LinearInterpolator());
animation.setDuration(1000);
animation.start();
}
另一种方法是使用自定义画布类。我为 ExampleDrawView mLittleChefDraw 创建了自己的自定义视图类,而不是 ImageView;在我的布局中。您可能不得不对它进行一些操作,才能准确地获得您在旋转方面所寻找的东西,我只是使用画布的中间作为支点进行了 360 度转动。
public class ExampleDrawView extends View {
Bitmap bitmap;
Float mRotate= 0f;
Handler h;
//State variables
final int STATE_PAUSE = 2;
final int STATE_ROTATE = 3;
int STATE_CURRENT;
public ExampleDrawView(Context context, AttributeSet attrs) {
super(context, attrs);
h = new Handler();
bitmap= BitmapFactory.decodeResource(getResources(), R.drawable.dish_special);
STATE_CURRENT= STATE_PAUSE;
}
Runnable move = new Runnable() {
@Override
public void run() {
switch (STATE_CURRENT){
case STATE_ROTATE:
if (mRotate<360){
mRotate++;
invalidate();
}else{
STATE_CURRENT= STATE_PAUSE;
}
h.postDelayed(move, 20);
break;
}
}
};
public void startDrawing(){
if(STATE_CURRENT == STATE_PAUSE){
STATE_CURRENT= STATE_ROTATE;
mRotate=(float) 0;
h.postDelayed(move, 20);
}
}
@Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
//change your rotate point here, i just made it the middle of the canvas
canvas.rotate(mRotate,getWidth()/2,getHeight()/2);
canvas.drawBitmap(bitmap, 0, 0, null);
}
}
然后在活动中调用这个来启动它:
public void doCanvasCustomView(){
mLittleChefDraw.startDrawing();
}