这是我在指定位置的图像上绘制矩形的代码。绘制了矩形,但我的问题是现在我的图像没有显示。
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);
请告诉我的代码有什么问题吗?
答案 0 :(得分:1)
试试这个
Bitmap bm = new BitmapFactory().decodeResource(getResources(), your_image_id, Bitmap.Config.ARGB_8888);
Bitmap bitmap = Bitmap.createBitmap(bm);
Canvas canvas = new Canvas(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);
imageView.setImageBitmap(bitmap);
答案 1 :(得分:1)
您已将StrokeWidth
设为50
。这是非常巨大的。删除它或减少。否则代码可以绘制矩形。
我尝试了以下代码。
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);
修改强>
您可以尝试以下布局
<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>
其中,两个视图位于RelativeLayout中。一个是图像视图,第二个是用于绘制矩形的自定义视图。您的ImageView将与第二个重叠。第二种观点具有透明度因此,这看起来就像是在原始图像上绘制矩形。
答案 2 :(得分:0)
你需要先将图像变为可变图像,然后在其上绘制矩形并使其变为不可变 -
bitmap3=mutableimage3.copy(Bitmap.Config.ARGB_4444,true);// mutable image.
bitmap3=mutableimage3.copy(Bitmap.Config.ARGB_4444,false);//immutable