简体   繁体   中英

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.

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() - eg myImageView.getImageMatrix()

我认为在你的bitmap之外绘制的内容会丢失,你可以通过旋转你的ImageView来检查这一点,你会看到你的bitmap外面的东西是黑色的,即使你画了它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM