Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw rectangle Over ImageVIew

Tags:

java

android

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..

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..

like image 498
Bhavna Avatar asked Oct 28 '13 07:10

Bhavna


1 Answers

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:

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

like image 99
Amulya Khare Avatar answered Oct 05 '22 22:10

Amulya Khare