Solve the Problem of stretching the background image of android: background

Source: Internet
Author: User

Differences between the XML Attribute src and background in ImageView:

Background is stretched Based on the length and width specified by the ImageView component, while src stores the source image size and does not stretch. Src is the image content (foreground), bg is the background, and can be used at the same time.

In addition:ScaleType only applies to src; bg can set transparency. For example, in ImageButton, android: scaleType can be used to control the scaling mode of images.


As mentioned above, the image set by the background will be stretched according to the length/width ratio specified by the View component. For example, the 36x36 px icon is placed in the xhdpi folder. In the 854x480 (FWVGA, corresponding to hdpi) environment

Xhdpi: hdpi: mdpi: ldip = 2: 1.5: 1: 0.75

In FWVGA, the actual size of the icon should be 27x27.

However, when I put it in a LinearLayout with layout_width = 96px and layout_height = 75px, the layout code is as follows:

 
      
 

The actual situation is that the size of ImageButton is 33x27, and the width is obviously stretched. This is what we don't want to see.

Solution 1:

The code dynamically and explicitly sets the layout_width and layout_width of ImageButton, as shown below:

LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(27, 27);layout.addView(imageButton, layoutParam);
However, in fact, we do not want the code to be hard-coded.

Solution 2:

When you set the android: background attribute through setBackgroundResource () or xml, define your background as an XML Bitmap, as follows:

 
 
The call is as follows:

ImageButton. setBackgroundResource (R. drawable. toolbar_bg_bmp)

Or

If the background image has multiple statuses, you can refer to toolbar_bg_selector.xml:

 
     
  
       
      
          
       
  
 


In this way, the background is not stretched whether it is set by setBackgroundResource () or XML android: background in code mode.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.