自定义View_留声机效果
(Values下)attrs.xml
[html] view plain copy
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="GramophoneView">
<attr name="picture_radiu" format="dimension"/> //中间图片的半径
<attr name="src" format="reference"/> //图片
<attr name="disk_rotate_speed" format="float"/> //唱片旋转的速度
</declare-styleable>
</resources>
自定义View
[java] view plain copy
public class GramophoneView extends View {
/**
* 尺寸计算设计说明:
* 1、唱片有两个主要尺寸:中间图片的半径、黑色圆环的宽度。
* 黑色圆环的宽度 = 图片半径的一半。
* 2、唱针分为“手臂”和“头”,手臂分两段,一段长的一段短的,头也是一段长的一段短的。
* 唱针四个部分的尺寸求和 = 唱片中间图片的半径+黑色圆环的宽度
* 唱针各部分长度 比例——长的手臂:短的手臂:长的头:短的头 = 8:4:2:1
* 3、唱片黑色圆环顶部到唱针顶端的距离 = 唱针长的手臂的长。度
*/
private final float DEFUALT_DISK_ROTATE_SPEED = 1f; //磁盘旋转的速度
private final float DEFUALT_PICTURE_RAUID = 200; //中间图片默认半径
private final float DEFUALT_PAUSE_NEEDLE_DEGREE = -45; //暂停状态时唱针的旋转角度
private final float DEFUALT_PLAYING_NEEDLE_DEGREE = -15; //播放状态时唱针的旋转角度
private int pictrueRadio; //中间图片的半径
//指针
private int smallCircleRadiu = 10; //唱针顶部小圆半径,减小了一半
private int bigCircleRadiu = 15; //唱针顶部大圆半径,减小了一半
private int shortArmLength;
private int longArmleLength; // 唱针手臂,较长那段的长度
private int shortHeadLength; // 唱针的头,较短那段的长度
private int longHeadLength;
private Paint needlePaint;
//唱片
private float halfMeasureWidth;
private int diskRingWidth; // 黑色圆环宽度
private float diskRotateSpeed; // 唱片旋转速度
private Bitmap pictureBitmap;
private Paint diskPaint;
//状态控制
private boolean isPlaying;
private float currentDiskDegree; // 唱片旋转角度
private float currentNeddleDegree = DEFUALT_PLAYING_NEEDLE_DEGREE; // 唱针旋转角度
public GramophoneView(Context context) {
this(context,null);
}
public GramophoneView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
needlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);//抗锯齿
diskPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.GramophoneView);
// 拿到xml中的图片和图片半径和,旋转的度数
pictrueRadio = (int) typedArray.getDimension(R.styleable.GramophoneView_picture_radiu, DEFUALT_PICTURE_RAUID);
diskRotateSpeed = typedArray.getFloat(R.styleable.GramophoneView_disk_rotate_speed, DEFUALT_DISK_ROTATE_SPEED);
Drawable drawable = typedArray.getDrawable(R.styleable.GramophoneView_src);
if (drawable == null) {
pictureBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
} else {
pictureBitmap = ((BitmapDrawable)drawable).getBitmap();
}
//初始化唱片的变量
diskRingWidth = pictrueRadio >> 1;
shortHeadLength = (pictrueRadio + diskRingWidth) / 15; //图片半径和黑色圆环的和 等于 指针的总长度
longHeadLength = shortHeadLength << 1; //左移相当于乘以2
shortArmLength = longHeadLength << 1;
longArmleLength = shortArmLength << 1;
}
/**
* 理想的宽高是,取决于picture的 半径的
*
* @param widthMeasureSpec
* @param heightMeasureSpec
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//我们想要的理想宽高
int width = (pictrueRadio+diskRingWidth)*2;
int hight = (pictrueRadio+diskRingWidth)*2+longArmleLength;