Android中如何将ImageView设置为可水平垂直重复的边框?


如图中内容图片所示,我该如何将ImageView设置为可在水平和垂直方向重复的边框?
实现方法
方法一:用BitmapDrawable实现全图重复边框
如果你的边框素材是可以无缝重复的图案,直接通过XML Drawable就能实现:
- 将边框图片放入
res/drawable目录 - 创建
res/drawable/repeat_border.xml文件:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 第一层:ImageView的内容图片 --> <item android:drawable="@drawable/your_content_image" /> <!-- 第二层:重复的边框图案 --> <item> <bitmap android:src="@drawable/your_border_image" android:tileMode="repeat" /> </item> </layer-list>
- 在布局中给ImageView设置该Drawable:
<ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/repeat_border" />
方法二:自定义Drawable实现边缘边框重复
如果需要边框仅在ImageView的上下左右边缘重复,而非覆盖整个视图,可自定义Drawable:
public class RepeatBorderDrawable extends Drawable { private final Bitmap mBorderBitmap; private final Paint mPaint; public RepeatBorderDrawable(Bitmap borderBitmap) { mBorderBitmap = borderBitmap; mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); // 设置重复渲染模式 mPaint.setShader(new BitmapShader(borderBitmap, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT)); } @Override public void draw(@NonNull Canvas canvas) { Rect bounds = getBounds(); int borderWidth = mBorderBitmap.getWidth(); int borderHeight = mBorderBitmap.getHeight(); // 绘制顶部边框 canvas.drawRect(bounds.left, bounds.top, bounds.right, bounds.top + borderHeight, mPaint); // 绘制底部边框 canvas.drawRect(bounds.left, bounds.bottom - borderHeight, bounds.right, bounds.bottom, mPaint); // 绘制左侧边框 canvas.drawRect(bounds.left, bounds.top, bounds.left + borderWidth, bounds.bottom, mPaint); // 绘制右侧边框 canvas.drawRect(bounds.right - borderWidth, bounds.top, bounds.right, bounds.bottom, mPaint); } @Override public void setAlpha(int alpha) { mPaint.setAlpha(alpha); } @Override public void setColorFilter(@Nullable ColorFilter colorFilter) { mPaint.setColorFilter(colorFilter); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } }
在代码中给ImageView设置:
Bitmap borderBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.your_border_image); RepeatBorderDrawable borderDrawable = new RepeatBorderDrawable(borderBitmap); // 设置边框为背景,src放内容图片 imageView.setBackground(borderDrawable); imageView.setImageResource(R.drawable.your_content_image);
内容的提问来源于stack exchange,提问作者Rumiz
相关产品推荐
相关产品推荐

