This is my code to draw rectangle over an image in specified position. rectangle is drawn but my problem is that now my image is not shown.
Bitmap bitmap = Bitmap.createBitmap(50, 50, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
imageView.setImageBitmap(bitmap);
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(50);
float left = 20;
float topy = 20;
float right = 50;
float bottom = 50;
canvas.drawRect(left, topy, right, bottom, paint);
Please tell anything wrong on my code ?
You have set StrokeWidth
to 50
. which is very huge. Either remove it or decrease. Otherwise code is fine to draw rectangle.
I tried following code.
Bitmap bitmap = Bitmap.createBitmap(50, 50, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
button.setImageBitmap(bitmap);
Paint paint = new Paint();
paint.setColor(Color.BLACK); // canvas background fill
canvas.drawPaint(paint); // just to check how big rectangle draw on canvas
//you can remove 2 above lines. its my testing
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(5); //5 instead of 50
float left = 20;
float topy = 20;
float right = 50;
float bottom = 50;
canvas.drawRect(left, topy, right, bottom, paint);
Edit
You can try following layout
<LinearLayout
android:id="@+id/linearParentHolder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:gravity="center" >
<RelativeLayout
android:id="@+id/relativeHolder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center" >
<ImageView
android:id="@+id/imgMainImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:contentDescription="@string/app_name"
android:scaleType="fitCenter" />
<com.customview.CustomRectangleOverlayView
android:id="@+id/photoSortrView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/imgMainImage"
android:layout_alignLeft="@+id/imgMainImage"
android:layout_alignRight="@+id/imgMainImage"
android:layout_alignTop="@+id/imgMainImage" />
</RelativeLayout>
</LinearLayout>
In which, two views are in RelativeLayout. One is image view, Second is your Custom View which is used to draw rectangles. Your ImageView will be overlaped with second one. Second view has transparency. So, this will look like you are drawing rectangle on original image.