在Java中,是否可能以动态方式将位图添加为Android ImageView的边框?
我已经尝试了以下内容:
使用XML中的ImageView和形状作为边框,结果是错误的,我想要在边框中添加位图。
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke android:width="1px" android:color="#ff0000" />
<solid android:color="@android:color/transparent"/>
</shape>
<ImageView
android:id="@+id/unreserved_head_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:foreground="@drawable/shape_border"
/>
您有多种选择:
在您的ImageView上方添加一个带边框的其他视图(也是ImageView),这可能是最简单的解决方案。只需向xml添加另一个视图并确保它们重叠即可。(例如使用RelativeLayout或FrameLayout作为容器)
使用层列表,在位图上方绘制一个形状,并将其添加到您的ImageView中
编写自定义ImageView并使用Canvas在重写的onDraw方法中绘制边框。例如canvas.drawRect(...)非常简单明了。
"Theme.MaterialComponents.Light"
,然后在内部使用图像视图和材料卡片视图。 <com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardBackgroundColor="@color/white"
app:cardCornerRadius="8dp"
app:cardElevation="0dp"
app:strokeColor="@color/colorPrimary"
app:strokeWidth="1dp">
<ImageView/>//define you image view hear
</com.google.android.material.card.MaterialCardView>
stokeColor
和strokeWidth
,您可以在图像视图上创建边框并使其动态。在Android Studio中,您可以使用9 patch制作图像边框!
我曾寻找解决方案,但没有找到,所以我跳过了那一部分。
然后我去Firebase资产的Google图片上偶然发现他们使用9patch。
这是链接: https://developer.android.com/studio/write/draw9patch 你只需要拖动边缘位置
就像在Unity中的边框边缘一样简单