實現動態背景的方法有很多種,以下是其中一種實現方式:
以下是一個實現動態背景的例子:
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" />
以上代碼實現了一個不斷旋轉的矩形背景,你可以根據需要進行修改。