因为公司最近接了个音箱项目,需要写app控制音箱,有个需求是实现跑马灯效果:需要定义一个圆圈,手指滑动圆圈的同时控制音箱的跑马灯,因为音箱的跑马灯有36个状态灯围成一个圈,因此需要在滑动的时候计算触摸位置和圆中心的角度,从而决定打开哪个状态灯,同时还要能修改跑马灯的颜色。
实现思路:
1.利用shape画出圆圈
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadiusRatio="6"
android:shape="ring"
android:thicknessRatio="4"
android:useLevel="false">
<gradient
android:centerColor="#ff0000"
android:endColor="#0ff676"
android:startColor="#B23AEE"
android:useLevel="false" />
</shape>
2.自定义view,重写onTouchEvent()方法对触摸事件进行处理计算得出角度,在activity中加入自定义的view,并设置background为shape.xml
package com.skyworth.car.rulerdemo;
import android.content.Context;
import android.content.IntentFilter;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
/**
* @Author: david.lvfujiang
* @Date: 2019/12/12
* @Describe:
*/
public class ShapeView extends View {
int centerX, centerY;
private angleCallbackListener angleCallbackListener;
public void setAngleCallbackListener(ShapeView.angleCallbackListener angleCallbackListener) {
this.angleCallbackListener = angleCallbackListener;
}
public ShapeView(Context context) {
super(context);
}
public ShapeView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public ShapeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public ShapeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes)