我正在练习一些自定义视图。我成功地将画布平移到居中并旋转一定距离的圆(就像风扇一样),效果很好。
但是现在我想像旋钮一样在210度到150度之间旋转该圆。我将尝试添加到
if(theta == 210 || theta == 150)
theta *= -1;
但是它不能正常工作...
public class RoundMovingView extends View {
private static final String TAG = "CustomDrawing";
private float circleRadius = 50;
private float radius = 300;
double theta = 150.0;
private Paint circlePaint;
public RoundMovingView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
setFocusable(true);
setFocusableInTouchMode(true);
setupPaint();
}
private void setupPaint() {
circlePaint = new Paint();
circlePaint.setColor(Color.BLACK);
circlePaint.setAntiAlias(true);
circlePaint.setStrokeWidth(4);
circlePaint.setStyle(Paint.Style.STROKE);
circlePaint.setStrokeJoin(Paint.Join.ROUND);
circlePaint.setStrokeCap(Paint.Cap.ROUND);
}
@Override
protected void onDraw(Canvas canvas) {
///super.onDraw(canvas);
canvas.translate(getWidth()/2,getHeight()/2);
//Center Circle
circlePaint.setColor(Color.BLACK);
float center_circle_X = (float) (radius * Math.cos(theta));
float center_circle_Y = (float) (radius * Math.sin(theta));
canvas.drawCircle(center_circle_X, center_circle_Y, circleRadius, circlePaint);
canvas.drawLine(center_circle_X,center_circle_Y,0,0,circlePaint);
theta += .05;
if(theta == 210 || theta == 150)
theta *= -1;
invalidate();
requestLayout();
}
}
activity_splashy.xml
<?xml version="1.0" encoding="utf-8"?>
<c.customviewpracticing.RoundMovingView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/custom_relative_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context=".Splashy">
</c.customviewpracticing.RoundMovingView>