Kathir
Kathir

Reputation: 4377

Draw canvas drawRect with dynamic co ordinates

I am having canvas which will generate rectangle co-ordinates in image.

enter image description here

In this image need to draw rectangle shape on above Icon using canvas co-ordinates

My sample code

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

My Co-ordinates

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

I got output like this enter image description here

Upvotes: 0

Views: 617

Answers (1)

Marcos Vasconcelos
Marcos Vasconcelos

Reputation: 18276

You are copying the Bitmap into memory and never displaying, draw on the one that you set as ImageResource:

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

If you need to copy as ARGB_8888 then

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

As for your coordinates:

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

They are (X,Y,W,H) while Android Rectangles are (L,T,R,B)

To convert your coordinates use:

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

Then draw the area into the Canvas.

Upvotes: 1

Related Questions