在Android画布中旋转圆圈,可以通过以下步骤实现:
以下是一个示例代码:
public class CircleView extends View {
private Paint mPaint;
private float mRotation;
public CircleView(Context context) {
super(context);
init();
}
public CircleView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public CircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setAntiAlias(true);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
int radius = Math.min(centerX, centerY) - 10;
canvas.rotate(mRotation, centerX, centerY);
canvas.drawCircle(centerX, centerY, radius, mPaint);
}
public void setRotation(float rotation) {
mRotation = rotation;
invalidate();
}
}
在Activity或Fragment中使用该自定义View类:
public class MainActivity extends AppCompatActivity {
private CircleView mCircleView;
private float mRotation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCircleView = findViewById(R.id.circle_view);
// 通过定时器不断更新旋转角度,实现圆圈的旋转效果
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
mRotation += 5;
runOnUiThread(new Runnable() {
@Override
public void run() {
mCircleView.setRotation(mRotation);
}
});
}
}, 0, 50);
}
}
在布局文件中添加CircleView:
<com.example.CircleView
android:id="@+id/circle_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
这样就可以在Android画布中实现旋转的圆圈效果了。
领取专属 10元无门槛券
手把手带您无忧上云