用Android studio 画一个绕中心顺时针旋转的小圆形,每2秒旋转22.5度
时间: 2024-04-08 16:34:44 浏览: 60
Android Studio中,将两个项目合并到一个项目中
好的,请等一下,我给您展示一下代码。稍后将会显示一个旋转的小圆形。
```java
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
public class RotatingCircleView extends View {
private Paint circlePaint;
private int circleRadius;
private float rotationAngle;
public RotatingCircleView(Context context) {
super(context);
init();
}
public RotatingCircleView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public RotatingCircleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
circlePaint = new Paint();
circlePaint.setColor(Color.RED);
circleRadius = 50;
rotationAngle = 0;
}
@Override
protected void onDraw(Canvas canvas) {
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
canvas.rotate(rotationAngle, centerX, centerY);
RectF circleRect = new RectF(centerX - circleRadius, centerY - circleRadius,
centerX + circleRadius, centerY + circleRadius);
canvas.drawOval(circleRect, circlePaint);
}
public void startRotation() {
postDelayed(rotationRunnable, 2000);
}
private Runnable rotationRunnable = new Runnable() {
@Override
public void run() {
rotationAngle += 22.5f;
invalidate();
postDelayed(rotationRunnable, 2000);
}
};
}
```
请将这段代码放在您的项目中,并在您的布局文件中添加以下代码:
```xml
<com.yourpackage.RotatingCircleView
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
```
确保将 `com.yourpackage` 替换为您的包名。
接下来,在您的 Activity 或 Fragment 中,调用 `startRotation()` 方法来启动旋转动画。
```java
RotatingCircleView rotatingCircleView = findViewById(R.id.rotatingCircleView);
rotatingCircleView.startRotation();
```
这样就可以在屏幕上显示一个绕中心顺时针旋转的小圆形,每2秒旋转22.5度了。
阅读全文