我需要通过调用myView.setBackgroundDrawable(BitmapDrawable bdb)来动态设置布局的背景,但我想裁剪图像而不是在布局中拉伸它,有没有办法呢?
我试图创建下面的drawable来设置引力,但挑战是我无法将android:src硬编码为静态drawable,因为图像源必须是动态的。
<bitmap android:src="@drawable/background" android:gravity="center" />
任何建议都会非常感激!
答案 0 :(得分:1)
我相信您要查找的android:gravity
属性为clip_vertical
和clip_horizontal
,但需要提供建议。这些属性的行为可能与您认为的不同。您不能使用它们在两个方向上剪辑图像,只能剪切一个图像。以下代码:
<bitmap
android:src="@drawable/background"
android:gravity="clip_vertical|clip_horizontal" />
不允许在两个方向上裁剪图像...它实际上适合视图中的图像,就好像您没有设置任何一个。设置剪辑参数实际上设置该方向以适合视图,另一方向被裁剪也可能令人困惑。几个例子:
<!-- Force fit top/bottom, crop left/right with image centered -->
<bitmap
android:src="@drawable/background"
android:gravity="clip_vertical" />
<!-- Force fit top/bottom, align image left and crop right edge -->
<bitmap
android:src="@drawable/background"
android:gravity="left|clip_vertical" />
<!-- Force fit left/right, crop top/bottom with image centered -->
<bitmap
android:src="@drawable/background"
android:gravity="clip_horizontal" />
<!-- Force fit left/right, align top and crop bottom egde -->
<bitmap
android:src="@drawable/background"
android:gravity="top|clip_horizontal" />
请注意,这些设置允许裁剪大于视图的图像,但如果图像小于视图,则其内容仍将被拉伸以适合。为了管理图片在小于视图时在<bitmap>
标记中的行为方式,请查看tileMode
。请注意,tileMode
和gravity
不能一起使用;如果两者都包括在内,gravity
将被忽略。
如果您需要更多动态控制图像的缩放方式,并且您不想使用ImageView
,您还可以将生成的Drawable包装在ScaleDrawable
中并配置基于测量的视图大小,Java代码中的x / y比例百分比。
答案 1 :(得分:0)
答案 2 :(得分:0)
if (srcBmp.getWidth() >= srcBmp.getHeight()){
dstBmp = Bitmap.createBitmap(
srcBmp,
srcBmp.getWidth()/2 - srcBmp.getHeight()/2,
0,
srcBmp.getHeight(),
srcBmp.getHeight()
);
}else{
dstBmp = Bitmap.createBitmap(
srcBmp,
0,
srcBmp.getHeight()/2 - srcBmp.getWidth()/2,
srcBmp.getWidth(),
srcBmp.getWidth()
);
}