Android Canvas drawLine not drawing on MainActivit

2019-07-23 04:01发布

问题:

I want to draw a line on the Main Activity using Canvas. The problem is, it is not drawing anything. I have the following code:

 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);

回答1:

you can display the bitmap like that:

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

in your case you can try somthing like this:

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

but you need to use a diffrent canvas for it. The canvas wich let you draw stuff on your screen will be passed to your onDraw() method in your View. So you need to make a View class first and add it in your MainActivity.

You can do that like this: First you create a class called MyView and add this code to it:

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);
    }
}

then you change the code in your onCreate() method in your MainActivity to this:

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

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


回答2:

Create a class like this

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);
}
}