在Android中创建带边框的ImageView通常需要结合布局属性和自定义绘制技术。minWidth
是一个视图属性,用于指定视图的最小宽度,确保视图不会缩小到小于这个值。
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="100dp"
android:background="@drawable/image_border"
android:src="@drawable/your_image"
android:padding="4dp"/>
然后在res/drawable/image_border.xml
中创建边框:
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF"/> <!-- 背景色 -->
<stroke android:width="2dp" android:color="#000000"/> <!-- 边框 -->
<corners android:radius="4dp"/> <!-- 圆角 -->
</shape>
public class BorderedImageView extends androidx.appcompat.widget.AppCompatImageView {
private Paint borderPaint;
private int borderWidth = 4;
public BorderedImageView(Context context) {
super(context);
init();
}
public BorderedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
borderPaint = new Paint();
borderPaint.setStyle(Paint.Style.STROKE);
borderPaint.setColor(Color.BLACK);
borderPaint.setStrokeWidth(borderWidth);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(0, 0, getWidth(), getHeight(), borderPaint);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int minWidth = getSuggestedMinimumWidth();
int minHeight = getSuggestedMinimumHeight();
int width = resolveSizeAndState(minWidth, widthMeasureSpec, 0);
int height = resolveSizeAndState(minHeight, heightMeasureSpec, 0);
setMeasuredDimension(width, height);
}
}
然后在XML中使用:
<com.your.package.BorderedImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="100dp"
android:src="@drawable/your_image"/>
<androidx.cardview.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardCornerRadius="4dp"
app:cardElevation="0dp"
app:cardBackgroundColor="#000000"
android:padding="2dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="100dp"
android:src="@drawable/your_image"/>
</androidx.cardview.widget.CardView>
问题1:边框被图片覆盖
问题2:minWidth不生效
问题3:边框显示不全
以上方法都可以实现带边框的ImageView,选择哪种取决于具体需求和项目架构。
没有搜到相关的文章