我想选择图像的矩形区域,即图像视图中的位图。 rect区域由用户通过触摸定义。它不像作物。用户可以选择矩形区域,然后创建子图像。我在下面给出一些代码,它不是独立于设备,我也已经将OpenCv用于计算感兴趣的区域,请帮帮我
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DragRectView view = (DragRectView) findViewById(R.id.dragRect);
imview1 = (ImageView) findViewById(R.id.imageView1);
bmp = BitmapFactory.decodeResource(getResources(), R.drawable.poll);
imview1.setImageBitmap(bmp);
final Mat mat1=new Mat(bmp.getHeight(),bmp.getWidth(),CvType.CV_8UC4);
Utils.bitmapToMat(bmp, mat1);
if (null != view) {
view.setOnUpCallback(new DragRectView.OnUpCallback() {
@Override
public void onRectFinished(final Rect rect) {
org.opencv.core.Rect rectmat = new org.opencv.core.Rect(10,20,240,360);
Mat matroi = new Mat(mat1,rectmat);
Bitmap bm = Bitmap.createBitmap(matroi.rows(),matroi.cols(),Config.ARGB_8888);
Utils.matToBitmap(matroi, bm);
//mat1.copyTo(rectmat);
Toast.makeText(getApplicationContext(), "Rect is (" + rect.left + ", " + rect.top + ", " + rect.right + ", " + rect.bottom + ")",
Toast.LENGTH_LONG).show();
imview1.setImageBitmap(bm);
}
});
}
}
答案 0 :(得分:1)
此代码将帮助您使用Android.graphics.rect。
绘制矩形public int ImgYOffset;
public int ImgXOffset;
private rectangle_box = null;
final AtomicReference<Point> RectBox_1stCorner = new AtomicReference<Point>();
final Paint rectPaint = new Paint();
rectPaint.setColor(Color.rgb(0, 255, 0));
rectPaint.setStrokeWidth(5);
rectPaint.setStyle(Style.STROKE);
setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
final Point corner = new Point(event.getX() - ImgXOffset, event.getY() - ImgYOffset);
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
RectBox_1stCorner.set(corner);
break;
case MotionEvent.ACTION_UP:
rectangle_box= new Rect(RectBox_1stCorner.get(), corner);
break;
case MotionEvent.ACTION_MOVE:
final android.graphics.Rect rect = new android.graphics.Rect(
(int)RectBox_1stCorner.get().x + ImgXOffset, (int)RectBox_1stCorner.get().y + ImgYOffset,
(int)corner.x + ImgXOffset, (int)corner.y + ImgYOffset);
final Canvas canvas =_holder.lockCanvas(rect);
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); // remove old rectangle
canvas.drawRect(rect, rectPaint);
_holder.unlockCanvasAndPost(canvas);
break;
}
return true;
}
});
}
// if rectangle box is not null then assign this rectangle_box to new MAT or BITMAP object to create a subimage which you want to work with.