自定义View是android开发的一个重要技能,用android提供的2/3D绘制相关类可以实现非常多炫酷的效果,需要实打实的编程基础。(吧)。
但是自定义View又是我的弱项,所以最近都在摸索、练习自定义View。今天我写了一个圆形图片,同时不断匀速旋转的RotateCircleImageView。实现方法是自己想的,但肯定不是最好的实现方法。
自定义View分四步。
一:自定义属性;
二:创建自定义View,在构造方法中拿到自定义属性;
三:重写onMeasure方法;
四:重写onDraw方法
先来个效果图
先在res/values/下新建attrs.xml
自定义属性
<declare-styleable name="RotateCircleImageView">
<attr name="image" format="reference" />
<attr name="rotate_sd" format="float" />
<attr name="rotate_fx" format="integer" />
<attr name="isRotate" format="boolean" />
<attr name="circle_back_width" format="dimension" />
<attr name="circle_back_color" format="color" />
</declare-styleable>
创建RotateCircleImageView
public RotateCircleImageView(Context context) {
this(context, null);
}
public RotateCircleImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RotateCircleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initData();
}
重写View的三个构造函数,用一参的调用二参的,用二参的调用三参的。在三参的构造里初始化参数。
private Bitmap image;
private Bitmap tempImage;
private Paint paint;
private int bkWidth;//黑色圆边框的宽度
private int rotate_fx=0;//旋转方向 0=顺时针 1=逆时针
private float rotateSD = 0.8f;//每次旋转的角度--建议范围0.1f-1,否则会抖动
private boolean isRotate = false;//控制是否旋转
private void initData() {