RiadSaadi
RiadSaadi

Reputation: 401

Get the Height and the Width of drawn area of an ImageView

if I have an ImageView of (800*800 pixels). When I try to draw a line outside this ImageView it draws

    myBitmap = Bitmap.createBitmap(800,800,Bitmap.Config.ARGB_8888);
    myCanvas = new Canvas(myBitmap);
    myPaint = new Paint();
    myImageView.setImageBitmap(myBitmap);
    myCanvas.drawLine(-100, -100, 600, 600, myPaint);

this draw my line even if the start point is outside,

Now I want to obtain their total size, I mean [900 , 900]. I don't know from which component can I obtain it (myCanvas or myBitmap or myImageView).

I hope that my question is clear.

thank you.

Upvotes: 1

Views: 966

Answers (2)

user2366923
user2366923

Reputation:

I think that what is drawn outside your bitmap is lost, and you can check this by rotating your ImageView, you will see that what was outside your bitmap is black even if you drew ther.

Upvotes: 1

CodeWarrior
CodeWarrior

Reputation: 5176

I think what you require is :

Using ImageView.getDrawable().getInstrinsicWidth() and getIntrinsicHeight() will both return the original dimensions.

The only way to get the actual dimensions of the displayed image is by extracting and using the transformation Matrix used to display the image as it is shown. This must be done after the measuring stage and the example here shows it called in an Override of onMeasure() for a custom ImageView:

    public class SizeAwareImageView extends ImageView {

    public SizeAwareImageView(Context context) {
        super(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        // Get image matrix values and place them in an array
        float[] f = new float[9];
        getImageMatrix().getValues(f);

        // Extract the scale values using the constants (if aspect ratio maintained, scaleX == scaleY)
        final float scaleX = f[Matrix.MSCALE_X];
        final float scaleY = f[Matrix.MSCALE_Y];

        // Get the drawable (could also get the bitmap behind the drawable and getWidth/getHeight)
        final Drawable d = getDrawable();
        final int origW = d.getIntrinsicWidth();
        final int origH = d.getIntrinsicHeight();

        // Calculate the actual dimensions
        final int actW = Math.round(origW * scaleX);
        final int actH = Math.round(origH * scaleY);
    }
} 

Note: To get the image transformation Matrix from code in general (like in an Activity), the function is ImageView.getImageMatrix() - e.g. myImageView.getImageMatrix()

Upvotes: 2

Related Questions