实现动态背景的方法有很多种,以下是其中一种实现方式:
以下是一个实现动态背景的例子:
public class DynamicBackgroundView extends View {
private Paint paint;
private RectF rectF;
private float angle;
public DynamicBackgroundView(Context context) {
super(context);
init();
}
public DynamicBackgroundView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public DynamicBackgroundView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
rectF = new RectF();
angle = 0;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
rectF.set(0, 0, width, height);
canvas.save();
canvas.rotate(angle, width / 2, height / 2);
canvas.drawRoundRect(rectF, 20, 20, paint);
canvas.restore();
angle += 1;
if (angle >= 360) {
angle = 0;
}
invalidate(); // 触发重绘
}
}
在Activity中使用该自定义View类:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DynamicBackgroundView dynamicBackgroundView = findViewById(R.id.dynamic_background_view);
}
}
在布局文件中引入该自定义View类:
<com.example.myapplication.DynamicBackgroundView
android:id="@+id/dynamic_background_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
以上代码实现了一个不断旋转的矩形背景,你可以根据需要进行修改。