Android Canvas drawLine 未在 MainActivity 上绘制

Android Canvas drawLine not drawing on MainActivity

我想使用 Canvas 在 Main Activity 上画一条线。问题是,它没有画任何东西。我有以下代码:

 Bitmap bitmap = Bitmap.createBitmap(1920, 1080, Bitmap.Config.ARGB_8888);

Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(10);

float left = 20;
float top = 20;
float right = 50;
float bottom = 100;

canvas.drawLine(left, top, right, bottom, paint);

你可以这样显示位图:

canvas.drawBitmap(bmp, positionX, positionY, paint);

在你的情况下,你可以尝试这样的事情:

canvas.drawBitmap(bitmap, 0, 0, null);

但您需要使用不同的 canvas。 canvas 让您在屏幕上绘制内容的 canvas 将被传递给视图中的 onDraw() 方法。所以你需要先做一个Viewclass然后添加到你的MainActivity中。

你可以这样做: 首先创建一个名为 MyView 的 class 并向其添加以下代码:

public class MyView extends View {

    Bitmap bitmap;

    public MyView(Context context) {
        bitmap = Bitmap.createBitmap(1920, 1080, Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        paint.setStrokeWidth(10);

        float left = 20;
        float top = 20;
        float right = 50;
        float bottom = 100;

        canvas.drawLine(left, top, right, bottom, paint);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(bitmap, 0, 0, null);
        super.onDraw(canvas);
    }
}

然后将 MainActivity 中的 onCreate() 方法中的代码更改为:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);  

    MyView myView = new MyView(this);
    setContentView(myView);
}

像这样创建一个class

public class MyView extends View {
public MyView(Context context) {
    super(context);
}

public MyView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

@Override
protected void onDraw(Canvas canvas) {
    Paint paint = new Paint();
    paint.setColor(Color.BLACK);
    paint.setStyle(Paint.Style.FILL_AND_STROKE);
    paint.setStrokeWidth(10);

    float left = 20;
    float top = 20;
    float right = 50;
    float bottom = 100;

    canvas.drawLine(left, top, right, bottom, paint);
}
}