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);

}

}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐