【问题标题】:Programatically setting background of LinearLayout is stretching the image以编程方式设置 LinearLayout 的背景正在拉伸图像
【发布时间】:2013-08-23 22:36:59
【问题描述】:

如何在不拉伸图像的情况下将 LinearLayout 的背景设置为特定图像(从 Internet 获取)?

基本上,我有以下代码将 Bitmap 转换为 BitmapDrawable,这反过来又允许我以编程方式设置 LinearLayout 的背景:

BitmapDrawable myBackground = new BitmapDrawable(myBitmap);
myLinearLayout.setBackgroundDrawable(myBackground);

问题是,图像拉伸以匹配 LinearLayout 的高度和宽度;它不会像我在 XML 布局中将背景设置为可绘制那样水平和垂直居中。如何使用从 Internet 检索的位图实现此目的?

【问题讨论】:

  • 尽量不要改变背景层,用于ImageView。如何设置图片大小:image_view.getLayoutParams().height = 50;,image_view.getLayoutParams().width = 50;

标签: android


【解决方案1】:

只需在您的 linearLayout 后面使用一个 imageView(使用另一个 viewGroup,如 relativeLayout 来实现)并相应地设置 imageView 的 scaleType... (http://etcodehome.blogspot.co.at/2011/05/android-imageview-scaletype-samples.html)

【讨论】:

    【解决方案2】:

    这是因为 backgroundDrawable 无权更改父布局的布局参数。

    你有两个选择:

    1 -

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="center" />
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    </LinearLayout>
    </FrameLayout>
    

    2 - 手动设置LinearLayout的大小

    BitmapDrawable myBackground = new BitmapDrawable(myBitmap);
    LayoutParams lp = myLinearLayout.getLayoutParams();
    lp.width = myBitmap.getWidth();
    lp.height = myBitmap.getHeight();
    myLinearLayout.setlayoutParams(lp)
    myLinearLayout.setBackgroundDrawable(myBackground);
    

    你应该重写 BitmapDrawable 的 onDraw(Canvas c) 方法,在中心绘制位图 现在看起来像:http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.3_r2.1/android/graphics/drawable/BitmapDrawable.java#BitmapDrawable.draw%28android.graphics.Canvas%29

    【讨论】:

    • 第二个选择是改变布局大小,你不能通过改变我认为的其他东西来做到这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-12
    • 2012-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    相关资源
    最近更新 更多