Android Canvas drawLine不在MainActivity上绘图

时间:2015-03-01 11:59:54

标签: java android android-activity canvas draw

我想使用Canvas在主要活动上画一条线。问题是,它没有绘制任何东西。我有以下代码:

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

2 个答案:

答案 0 :(得分:4)

你可以像这样显示位图:

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

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

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

但你需要使用不同的画布。允许您在屏幕上绘制内容的画布将传递到视图中的onDraw()方法。因此,您需要先创建一个View类,然后将其添加到MainActivity中。

你可以这样做: 首先,您创建一个名为MyView的类,并将此代码添加到其中:

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

答案 1 :(得分:1)

创建一个这样的类

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