如何在不拉伸图像的情况下,将LinearLayout的背景设置为特定的图像(这是从互联网上获取的)?
基本上,我有以下代码,它将位图转换为BitmapDrawable,这反过来允许我以编程方式设置LinearLayout的背景:
BitmapDrawable myBackground = new BitmapDrawable(myBitmap);
myLinearLayout.setBackgroundDrawable(myBackground);
问题是,图像延伸到与LinearLayout的高度和宽度相匹配;它不会像我将背景设置为可绘制的XML布局那样水平和垂直地对其进行居中。如何通过从互联网上检索到的位图实现这一目标?
发布于 2013-08-21 14:23:46
只需在imageView后面使用linearLayout (使用另一个viewGroup (如relativeLayout )来实现这一点),并相应地设置imageView的scaleType .(http://etcodehome.blogspot.co.at/2011/05/android-imageview-scaletype-samples.html)
发布于 2013-08-21 15:11:56
之所以发生这种情况,是因为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- setSize of LinearLayout用你的手
BitmapDrawable myBackground = new BitmapDrawable(myBitmap);
LayoutParams lp = myLinearLayout.getLayoutParams();
lp.width = myBitmap.getWidth();
lp.height = myBitmap.getHeight();
myLinearLayout.setlayoutParams(lp)
myLinearLayout.setBackgroundDrawable(myBackground);
您应该重写onDraw(画布c)方法的BitmapDrawable,在中间绘制位图,现在它看起来像:r2.1/android/graphics/drawable/BitmapDrawable.java#BitmapDrawable.draw%28android.graphics.Canvas%29
https://stackoverflow.com/questions/18359414
复制相似问题