android中相对于屏幕宽度缩放图像
我有一个包含两个图像的布局:
- 一个应该拉伸到屏幕宽度,
- 上面一个应该缩放到与第一个图像自动缩放相同的比例(相对于原始图像大小)
更具体:这两个图像是同一图像的切片,因此它们内部的一些细节应该匹配。
我可以用 XML 来做这个吗?
如果我不能通过 XML 做到这一点,也许我可以预先缩放图形。在这种情况下,我应该如何预缩放它们?
I have a layout with two images:
- one that should strech to the screen width
- one above it that should scale to the same proportion the first one was automaticaly scaled (relative to the original image size)
More specific: the two images are slices of the same image, and therefore some details inside them should match.
Can I make this in XML?
If I cannot do it through XML, maybe I could prescale the graphics. In this case, how should I prescale them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这有点像 hack,但它允许您在 xml 中执行此操作。
例如,如果您知道顶部图像的大小是底部图像大小的 X%,那么您可以使用 LinearLayout 的layout_weight 根据屏幕百分比来定位顶部图像并调整其大小:
上面的示例会将 top_image 的大小设置为 50屏幕的 %,距左侧偏移 20%。只要 top_image 的大小是 Bottom_image 的 50%,就会保持相似的比例。
或者,“正确”的方法可能是覆盖 onDraw() 在自定义视图中并使用画布绘制方法。
This is a bit of a hack, but it would allow you to do this in xml.
If you know that, for example, the top image is X% of the size of the bottom one, then you can use LinearLayout's layout_weight to position and size the top image in terms of percentage of the screen:
The above would size top_image at 50% of the screen with an offset of 20% from the left. As long as top_image is 50% the size of bottom_image, this will keep similar scale.
Alternatively, the "right" way to do this is probably to override onDraw() in a custom view and use canvas drawing methods.
您可以使用
Canvas
类方法drawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint Paint)
用于通过自动缩放/平移来填充目标矩形来绘制指定的位图。这可用于具有不同矩形的位图。可以通过除以布局的当前宽度和高度来制定矩形。这样程序就会根据不同屏幕尺寸的设备缩放图像。
You could use the
Canvas
class methoddrawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint paint)
for drawing the specified bitmap by scaling/translating automatically to fill the destination rectangle. This can be used for both the bitmaps with different Rect. The Rect can be formulated by dividing the current width and height of the layout. So that the program will scale the images in accordance with devices having different screen size.