简体   繁体   中英

Android - Set Drawable to Canvas but keep Aspect Ratio

I'm having a small issue with my android code . This is the first time i'm using canvas and i want to set an image to it but keep some type of aspect ratio.

This is what i'm doing right now and this maps the image onto the canvas completely . It sets the image width-height to canvas width-height.

Drawable drawable = image;  // gets the image

drawable.SetBounds(0, 0, canvasWidth, canvasHeight);

drawable.Draw(canvas);

This works well on certain devices but when the device is large , the stretching is really bad . I want to set the bounds in such a way that it keeps an aspect ratio . If the canvas width-height is not the same aspect ratio , it will try to fill the canvas with an aspect ratio but might leave some space off in x or y axis .

int imgWidth = 500;
int imgHeight = 800;

I want to map the image on the canvas based on these values and stretch as necessary but keeping this aspect ratio even if part of the canvas is not filled .

What is the best way to do this ?

Thanks

I've already answered a similar question here .

To preserve the aspect ratio I did this:

val drawable = resources.getDrawable(R.drawable.my_vector, null)
val aspectRatio = drawable.intrinsicWidth.toFloat() / drawable.intrinsicHeight
val desiredWidthInPx = 100 // could be your view size or canvas size
val derivedHeightInPx = (desiredWidthInPx / aspectRatio).toInt()
drawable.setBounds(0, 0, desiredWidthInPx, derivedHeightInPx)
drawable.draw(canvas)

The above is for when the drawable width is smaller than its height.
If the drawable height is larger than its width, then first set the height to your desired size and then calculate the width.

Provide correct images in each resource folder. Correct images means correct resolution and screen density. Refer to this link http://developer.android.com/guide/topics/resources/providing-resources.html

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