在Android屏幕上显示的Bitmap上没有显示

时间:2014-04-07 05:13:49

标签: android bitmap android-canvas

我在绘制位图时遇到了一些困难。我在下面发布了我的代码。我想要做的是我在新创建的位图上绘制一个矩形并将该位图添加到onDraw()的画布上。但是我没有让那个rect显示在屏幕上,但是如果我在onDraw方法中复制我的绘制rect代码它会显示在屏幕上,不知道我做错了什么。有人可以纠正我。谢谢:))

public class MyView extends View {
Bitmap bmp;
Path path;
Paint paint;

public MyView(Context context) {
    super(context);

    setMinimumHeight(400);
    setMinimumWidth(400);

    setupDrawing();
    square();
}

private void setupDrawing(){
    path = new Path();
    paint  = new Paint();

    paint.setColor(Color.GREEN);

}

public void square(){
    Bitmap.Config conf = Bitmap.Config.ARGB_8888;
    bmp = Bitmap.createBitmap(200, 200, conf);
    Canvas canvas = new Canvas(bmp);

     path.moveTo(0, 0);
     path.lineTo(getWidth()-50,0);
     path.lineTo(getWidth()-50, getHeight()-50);
     path.lineTo(0,getHeight()-50);
     path.lineTo(0, 0);
    canvas.drawPath(path, paint);

    invalidate();
}


@Override
protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);

    canvas.drawBitmap(bmp, 0, 0, paint);
}

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(getSuggestedMinimumWidth(),    getSuggestedMinimumHeight());
};

}

1 个答案:

答案 0 :(得分:1)

这是因为你从构造函数中调用函数 square()。那时不会创建视图, square()方法中的getWidth()和getHeight()将为零,因此不会在Bitmap上绘制路径。您可以从onMeasure方法获取视图宽度和高度。我已更改您的代码,请在下面找到,

public class MyView extends View {

private Bitmap bmp;
private Path path;
private Paint paint;
private int viewWidth, viewHeight;

public MyView(Context context) {
    super(context);
    setMinimumHeight(400);
    setMinimumWidth(400);
    setupDrawing();
}

private void setupDrawing() {
    path = new Path();
    paint = new Paint();
    paint.setColor(Color.GREEN);
}

public void square() {
    Bitmap.Config conf = Bitmap.Config.ARGB_8888;
    bmp = Bitmap.createBitmap(200, 200, conf);
    Canvas canvas = new Canvas(bmp);
    path.moveTo(0, 0);
    path.lineTo(viewWidth - 50, 0);
    path.lineTo(viewWidth - 50, viewHeight - 50);
    path.lineTo(0, viewHeight - 50);
    path.lineTo(0, 0);
    canvas.drawPath(path, paint);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    square();
    if (bmp != null)
        canvas.drawBitmap(bmp, 0, 0, paint);
}

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(getSuggestedMinimumWidth(),
            getSuggestedMinimumHeight());
    viewWidth = getSuggestedMinimumWidth();
    viewHeight = getSuggestedMinimumWidth();
};

}