根据屏幕宽度缩放Android中的图像

13

我有一个包含两张图片的布局:

  • 其中一张图片应该拉伸到屏幕宽度
  • 另一张图片在其上方,应该按照与第一张自动缩放的比例相同的比例进行缩放(相对于原始图像大小)

更具体地说,这两个图像是同一图像的切片,因此其中一些细节应该匹配。
我能用XML实现这个吗?

如果无法通过XML完成,则可以预先缩放图形。在这种情况下,应该如何预先缩放它们?


你解决了这个问题吗?顺便说一下,不确定你是否看到了我的关于你的Canvas.onDraw问题的答案更新。 - techi.services
不,还没有解决。我想我会用编程的方式来解决它。 - Iulius Curt
2个回答

6

这有点像是一个技巧,但它可以让你在XML中实现这个功能。

如果你知道,例如,顶部图像的大小是底部图像的X%,那么你可以使用LinearLayout的layout_weight属性来按照屏幕百分比定位和调整顶部图像的大小:

<LinearLayout android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <ImageView android:id="@+id/left_filler" android:layout_weight="20"
        android:layout_width="wrap_content" android:layout_height="wrap_content"/>
    <ImageView android:id="@+id/top_image" android:layout_weight="50"
        android:layout_width="wrap_content" android:layout_height="wrap_content"/>
    <ImageView android:id="@+id/right_filler" android:layout_weight="30"
        android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</LinearLayout>
 ... bottom image

上面的代码将 top_image 大小设为屏幕的 50%,并且从左边偏移了 20%。只要 top_image 的大小是 bottom_image 的 50%,这样可以保持相似的比例。

另一种方法可能是使用自定义视图中的 onDraw() 方法并使用画布绘图方法来覆盖它。


0
你可以使用Canvas类的方法drawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint paint)来绘制指定的位图,自动缩放/平移以填充目标矩形。这可用于具有不同Rect的位图。可以通过将布局的当前宽度和高度进行分割来制定Rect。因此,程序将根据具有不同屏幕尺寸的设备缩放图像。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接