用动态坐标绘制画布drawRect

时间:2017-11-28 12:28:59

标签: android canvas android-imageview

我有画布,会在图像中生成矩形坐标。

enter image description here

在此图像中,需要使用画布坐标

在上方的Icon上绘制矩形

我的示例代码

    @Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
    Log.e("PICASA", "Loaded");
    setImageBitmap(bitmap);
    Bitmap drawableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
    Canvas canvas = new Canvas(drawableBitmap);

    List<ClickableArea> clickableAreas = IBSTFragment.getClickableAreas();
    for (ClickableArea clickArea : clickableAreas) {
    Paint paint = new Paint();
    paint.setColor(Color.TRANSPARENT);
    paint.setStyle(Paint.Style.FILL);


    int x1 = clickArea.getX();
    int y1 = clickArea.getY();
    int w = clickArea.getW();
    int h = clickArea.getH();


    Rect rect = new Rect(x1, y1, w, h);



    // FILL
    canvas.drawRect(rect, paint);


    paint.setStrokeWidth(10);
    paint.setColor(Color.BLACK);
    paint.setStyle(Paint.Style.STROKE);
    canvas.drawRect(rect, paint);
    rect.width();
    rect.height();


}
    setImageBitmap(drawableBitmap);
}

我的坐标

X     Y  Width Height

600, 100, 50,   50
440, 125, 50,   50
685, 270, 50,   50
420, 350, 50,   50
370, 245, 50,   50
170, 280, 50,   50
30,  280, 50,   50
570, 250, 50,   50

我得到了这样的输出 enter image description here

1 个答案:

答案 0 :(得分:1)

您正在将位图复制到内存中并且从不显示,在您设置为ImageResource的那个上绘制:

setImageBitmap(bitmap);
Canvas canvas = new Canvas(bitmap);

如果您需要复制为ARGB_8888,那么

Bitmap drawableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(drawableBitmap);
//Draw everything, then after (at end of method)
setImageBitmap(drawableBitmap);

关于你的坐标:

X     Y  Width Height
600, 100, 50,   50
440, 125, 50,   50
685, 270, 50,   50
420, 350, 50,   50
...

它们是(X,Y,W,H),而Android矩形是(L,T,R,B)

要转换坐标,请使用:

 Rectangle area = new Rectangle(x, y, x + w, y + h);

然后将该区域绘制到画布中。