Whenever I assign background to a view that is laid out with wrap_content, if the background image is larger than a view, the view is stretched so that it can hold the entire background. Why is it so and how to prevent it? It occurs even if the image is 9-patch and has stretchable areas marked - why isn't the image shrunk to the size of the view?
1 Answer. Show activity on this post. The 100% 100% background-size value means the background should stretch (100%) of the width of the element and (100%) of the height of the element. Have either of them set to auto , which will size the undefined dimension automatically, while preserving the images aspect ratio.
Using CSS, you can set the background-size property for the image to fit the screen (viewport). The background-size property has a value of cover . It instructs browsers to automatically scale the width and height of a responsive background image to be the same or bigger than the viewport.
If you added the image and changed the dimensions right away the image will appear to be missing one of the dimensions. Word reads this incorrectly and in turn stretches the image. You can tell your image might do this because it's missing part of the dimensions like the image below.
Those images on the site you linked to are actual size, so the simple answer is just to resize the image. You can't really do this without "stretching" the image if the image happens to be less than 300px wide or tall, but you can do it without changing the ratio, which is what I think you mean.
You can use RelativeLayout and create two elements inside it. An ImageView for the Background and another view for your content. Use the android:layout_alignBottom
to the the ImageView and set the value to the id of your content view. Also set the scaleType of the ImageView to fitXY.
<RelativeLayout android:id="@+id/relativeLayout1"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_width="fill_parent">
<ImageView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:src="@drawable/chronometer_bg"
android:id="@+id/imageView_chronometerBackground"
android:layout_alignBottom="@id/chronometer" />
<Chronometer android:text="Chronometer"
android:id="@+id/chronometer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="32sp"
android:gravity="center" />
</RelativeLayout>
Either override the methods getSuggestedMinimumWidth and getSuggestedMinimumHeight of your layout view or the methods getMinimumWidth and getMinimumHeight of your background drawable to achieve that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With