Android 自定义View实现专辑图片不停旋转

原创
2017/04/14 15:58
阅读数 103

Android 自定义View实现专辑图片不停旋转

话不多说,直接上代码:

package com.example.hsaetest;

import android.content.Context;
import android.graphics.Canvas;
import android.os.Handler;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RotateView extends ImageView {
	private float degree;
	private int centerX, centerY;
	private Handler handler = new Handler();
	private Runnable runnable = new Runnable() {
		
		@Override
		public void run() {
			degree += 2f;
			if (degree > 360f) {
				degree -= 360f;
			}
			invalidate();
			handler.postDelayed(this, 16l);
		}
	};

	public RotateView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}
	
	public void start() {
		handler.post(runnable);
	}
	
	public void pause() {
		handler.removeCallbacks(runnable);
	}
	
	public void destroy() {
		handler.removeCallbacksAndMessages(null);
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		super.onSizeChanged(w, h, oldw, oldh);
		centerX = getWidth() / 2;
		centerY = getHeight() / 2;
	}
	
	@Override
	public void draw(Canvas canvas) {
		canvas.save();
		canvas.rotate(degree, centerX, centerY);
		super.draw(canvas);
		canvas.restore();
	}

	@Override
	protected void onDetachedFromWindow() {
		super.onDetachedFromWindow();
		handler.removeCallbacksAndMessages(null);
	}
}

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部