用动态坐标绘制canvas drawRect

Draw canvas drawRect with dynamic co ordinates

我有 canvas,它将在图像中生成矩形坐标。

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

在上方图标上绘制矩形形状

我的示例代码

    @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

我得到这样的输出

您正在将 Bitmap 复制到内存中并且从不显示,请在您设置为 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);

然后将区域绘制成Canvas。