通过背景图片实现圆角ImageView

4
我有两张图片 - 1)一个矩形的,显示实际内容,2)一个带圆角透明的白色图像。
是否可能将图像1放置在图像2中,保持其大小但使其成为与图像2相同的形状?
基本上我想让图像2成为图像1的容器。
我尝试过层和插入可绘制对象,但每次图像1都会重叠在图像2上。
提前致谢!
更新1:
这是我的ImageView xml部分:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="72dp"
android:orientation="horizontal">

    <ImageView
        android:id="@+id/avatar"
        android:src="@drawable/mainImg"
        android:background="@drawable/backgroundImg"
        android:layout_width="56dp"
        android:layout_height="56dp"
        android:layout_gravity="center"
        android:contentDescription="@string/desc" />

</LinearLayout>

更新2:

以下是三张图片的链接: 1)背景图 2)主图 3)期望的结果(带圆角)

ImageShack上传


你应该发布你的XML布局。 - Ovidiu Latcu
为什么不使用RelativeLayout来实现呢?您可以先放置包含图像的ImageView,然后在其上方放置框架图像。 - Cata
3个回答

4

一个简单的解决方案是只使用一个 ImageView,并为您的图像2使用 android:background,它是容器,而为图像1使用 android:src,它是实际图像:

<ImageView
    ...
    android:background="@drawable/image2"
    android:src="@drawable/image1"
    android:padding="2dp" />

只需要添加一个填充(padding)属性,指定你想在“框架”和实际“图片”之间留下多少空白即可。


很不幸,这个方法并没有像下面的答案那样有效。使用这个方法,我看到我的主要图像在背景图像内部带有一些白色边距,而我期望背景图像通过其形状裁剪主要图像。当我移除填充时,主要图像只是重叠在背景上! - Nznoonee
我已经更新了我的初始答案,并附上了三个图片链接。这将为您提供所期望的一些信息。我知道这可以通过形状来实现,但不幸的是我无法使用这种方法。 - Nznoonee
在这种情况下,您应该查看https://dev59.com/xHE95IYBdhLWcg3wGZ9_,因为您需要将图像的角落变圆。 - Ovidiu Latcu

4
我最近制作的应用程序中遇到了这个问题。请注意,在第一张和第二张截图中,所有的缩略图都被框起来了。
为了实现这个效果,我在FrameLayout中将图片和框架叠加在一起。首先布局实际的图像(@id/thumbnail),然后是框架(@id/frame)。
需要注意的重要事项是,缩略图使用了“fitXY”缩放类型,并且有一个轻微的边距,使得角落不会伸出在框架的圆角之后。
这只有在您的框架边框是不透明的情况下才能正常工作,因此您可能需要将框架边缘与背景颜色相同。
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="@dimen/thumbnail_size"
    android:layout_height="@dimen/thumbnail_size"
    android:layout_margin="5dp"
    android:gravity="center"
    android:orientation="vertical"
     >

    <ImageView
        android:id="@+id/thumbnail"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_margin="4dp"
        android:scaleType="fitXY" />

    <ImageView
        android:id="@+id/frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/pixel_frame"
        android:scaleType="fitXY" />

</FrameLayout>

3
使用ImageButton,将背景设置为Image1,将图像源设置为Image2。
        <ImageButton
            android:id="@+id/imageButton1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/image2"
            android:src="@drawable/image1" />

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