DarkWizard
DarkWizard

Reputation: 37

Unable to draw rectangle over imageview

I am Getting a problem drawing rectangle over imageview. Here is the peace of code. Xml is also there . my whole concern is if we can draw rect over imageview.??

protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.cropimage);
            paint=new Paint();
            bobj = new BaldBooth1();
            bm = BaldBooth1.bMap;
            d = new BitmapDrawable(bm);
            iv = ((ImageView) findViewById(R.id.image));
            iv.setImageDrawable(d);
            createRectInView(iv);

            ((ImageButton) findViewById(R.id.next)).setOnClickListener(this);

        }
        public void createRectInView(View v) {
            paint.setColor(Color.BLACK);
            paint.setStrokeWidth(3);
            canvas=new Canvas();
            canvas.drawRect(50, 50, 80, 80, paint);
            v.draw(canvas);


        }

Upvotes: 0

Views: 4951

Answers (1)

Daniel Chow
Daniel Chow

Reputation: 201

Your method createRectInView(View v) does not draw a rectangle over ImageView, it just create a canvas, draw a rectangle on that canvas, then draw the content of ImageView on that canvas, so it does not do what you expect.

Here is one possible resolution: you can extend ImageView and override its onDraw() method, for example..

public class ExtendedImageView extends ImageView {
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setStrokeWidth(3);
        canvas.drawRect(50, 50, 80, 80, paint);
    }
}

Updated:

Hi arun, I just test the code, and it works fine. Here are the details: for example, you can create the ExtendedImageView in package com.abc.widget, so in your cropImage.xml file, replace the <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="wrap_content"> to <com.abc.widget.ExtendedImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="wrap_content">. As you see, you only need to change the class name. Then changed the onCreate() method as:

protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.cropimage);
            bobj = new BaldBooth1();
            bm = BaldBooth1.bMap;
            d = new BitmapDrawable(bm);
            iv = ((ImageView) findViewById(R.id.image));
            iv.setImageDrawable(d);
            ((ImageButton) findViewById(R.id.next)).setOnClickListener(this);

        }

Upvotes: 2

Related Questions