简体   繁体   中英

How to keep the aspect ratio of a foreground image?

I currently have a FrameLayout with a background and a foreground image. The foreground image has transparency using alpha in order to see through and watch the background below.

The foreground image needs to mantain the same aspect ratio of the original bitmap because consists of a trasparent circle in a black screen, much like a spyglass effect. I'm looking for any resolution compatibility.

Unfortunately, I am incapable of achieve this and the foreground shows always its circle stretched.

This is part of the XML code:

<FrameLayout
    android:id="@+id/layout_parent"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/background"
    android:foreground="@drawable/foreground"
    android:foregroundGravity="center|fill_horizontal"
>

I am also trying to solve my issue providing two diferent images, one with 4:3 ratio and the other with 16:9 ratio, each one in a different drawable folder with the long and notlong qualifiers.

/drawable-long/foreground.png (16:9 aspect)

/drawable-notlong/foreground.png (4:3 aspect)

Still with no success.

Do you have any idea of how to get this effect?

Thanks for your time.

I don't believe you can change the scale type of either the foreground or the background. What I would recommend is to either:

  1. Place an extra ImageView in your FrameLayout to serve as your background, and use the src and scaleType attributes to handle the image and how it scales.

  2. Since it's a simple black background with just a transparent circle, you could convert that into a 9-patch, making sure to stretch it evenly around the circle. The circle will not scale, but the black area will extend to fill the view.

Number 1 is my personal recommendation if the circle needs to scale as well.

Change this attribute in your FrameLayout:

android:foregroundGravity="center"

This will place the foreground drawable in the center of the FrameLayout, not changing its size.

"center|fill_horizontal" will place it in the center and stretch its width to fill the FrameLayout width, which is clearly not what you want.

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