Java 在 ImageView 上绘制矩形
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19628797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Draw rectangle Over ImageVIew
提问by Bhavna
I want to implement a crop feature, where I want to have a small rectangle over an imageView. The rectangle should be static and I want to move the image and get the image to be cropped within the rectangular area. Then fetch the image within the rectangle as an cropped image. I have tried creating a canvas using Bitmap as a parameter but it doesn't worked. I have tried a lot to search how to do this. but couldn't find it anywhere. Please help..
我想实现一个裁剪功能,我想在 imageView 上有一个小矩形。矩形应该是静态的,我想移动图像并在矩形区域内裁剪图像。然后获取矩形内的图像作为裁剪图像。我曾尝试使用 Bitmap 作为参数创建画布,但它不起作用。我已经尝试了很多来搜索如何做到这一点。但在任何地方都找不到。请帮忙..
Bitmap bitmap=BitmapFactory.decodeResource(this.getResources(), R.drawable.indoor);
Bitmap mutBitmap = Bitmap.createBitmap(200, 400,bitmap.getConfig());
Canvas canvas = new Canvas(mutBitmap);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(10);
float leftx = 20;
float topy = 20;
float rightx = 50;
float bottomy = 100;
canvas.drawRect(leftx, topy, rightx, bottomy, paint);
I'm using the above code, but no rectangle is drawn on the imageView..
我正在使用上面的代码,但没有在 imageView 上绘制矩形。
回答by Amulya Khare
You need to put the drawing code in the onDraw()
method of the view for it to be shown. You should create a custom class that inherits from imageView, then override the onDraw()
method as below:
您需要将绘图代码放在onDraw()
要显示的视图的方法中。您应该创建一个继承自 imageView 的自定义类,然后重写该onDraw()
方法,如下所示:
class DrawView extends ImageView {
public DrawView(Context context) {
super(context);
}
DrawView(Context context, AttributeSet attrs) {
super(context, attrs);
}
DrawView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(10);
float leftx = 20;
float topy = 20;
float rightx = 50;
float bottomy = 100;
canvas.drawRect(leftx, topy, rightx, bottomy, paint);
}
}
Now in your layout, include DrawView
instead of your current ImageView
现在在您的布局中,包括DrawView
而不是您当前的ImageView