Android 裁剪背景
我有一个 LinearLayout
,宽度设置为 fill_parent
,高度设置为 wrap_content
。现在我想给它一个 png 文件的背景,但以传统方式执行会导致 LinearLayout 调整大小以显示整个背景,而不是裁剪附加部分。
如何设置 LinearLayout
的背景,使其不会调整大小?
谢谢
I have a LinearLayout
with width set to fill_parent
and height to wrap_content
. Now I want to give it a background from a png file, but doing it in a traditional way causes the LinearLayout
to resize in order to show the whole background instead of cropping the additional part.
How can I set the background of LinearLayout
so it won't resize?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看来这样的事情只能使用 ImageView 并相应地设置scaleType 参数来实现。一个快速的解决方法是使用
FrameLayout
并将ImageView
放在另一个具有透明背景的布局下。代码:
It appears that such thing is achievable only using the
ImageView
and setting thescaleType
parameter accordingly. A quick workaround is to useFrameLayout
and put theImageView
under another layout with transparent background.Code:
背景位图的默认行为是完全填充容器并根据需要增加容器的水平和垂直尺寸。解决方案是创建一个可绘制的位图资源并改变重力。
检查以下链接并查找可能的重力值。然后你的视图应该只引用可绘制资源,你应该没问题。
http://developer.android.com/guide/topics/resources/drawable-resource。 html#位图
The default behaviour of background bitmaps is to fill the container completely and grow the horizontal and vertical size of the container if needed. The solution is to create a drawable bitmap resource and changing the gravity.
Check the following link and look for the possible gravity values. Your view should then just reference the drawable resource and you should be fine.
http://developer.android.com/guide/topics/resources/drawable-resource.html#Bitmap
我通过子类化
LinearLayout
并覆盖onMeasure(int,int)
回调解决了这个问题,然后更新布局 XML 以使用我的新布局类型。我无权发布确切的代码,但我所做的是调用 super.onMeasure(int,int) 实现并检查测量的高度是否返回为我背景的确切高度图像。如果是这样,我会获取所有子视图的测量高度,然后计算新的高度值并将其传递给setMeasuredDimension(int,int)
。I solved this one by subclassing
LinearLayout
and overriding theonMeasure(int,int)
callback, then updating the layout XML to use my new layout type. I'm not at liberty to post that exact code, but what I did was invoke thesuper.onMeasure(int,int)
implementation and check whether the measured height came back as the exact height of my background image. If so, I grab the measured height of all child views, then calculate a new height value and pass it tosetMeasuredDimension(int,int)
.将此代码放入 xml 活动中,例如 Activity_main.xml
put this code in the xml activity, for example activity_main.xml