如果Android画布没有显示,可能是因为没有正确设置画布的尺寸或者画布没有正确添加到视图中。下面是一个可能的解决方法的代码示例:
public class CanvasView extends View {
private Paint paint;
private Canvas canvas;
private Bitmap bitmap;
public CanvasView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
paint = new Paint();
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(true);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// 创建一个与View尺寸相等的Bitmap作为画布
bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
// 创建一个Canvas对象,并将Bitmap设置为其画布
canvas = new Canvas(bitmap);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 在画布上绘制内容
canvas.drawCircle(getWidth() / 2, getHeight() / 2, Math.min(getWidth(), getHeight()) / 2, paint);
// 将画布内容绘制到View上
canvas.drawBitmap(bitmap, 0, 0, null);
}
}
public class MainActivity extends AppCompatActivity {
private CanvasView canvasView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
canvasView = findViewById(R.id.canvas_view);
}
}
这个示例代码演示了如何创建一个自定义视图CanvasView,并在该视图中绘制一个红色的圆形。请确保在布局文件中正确添加CanvasView,并在Activity或Fragment中正确初始化和使用CanvasView。