Android 在 ImageView 中绘制边框
Posted
技术标签:
【中文标题】Android 在 ImageView 中绘制边框【英文标题】:Android draw border in ImageView 【发布时间】:2011-11-29 09:43:53 【问题描述】:我想在图像周围画一个边框。但是我无法对齐 ImageView 本身的边框(就像大多数情况下一样),因为我使用 ImageMatrix 翻译和缩放 ImageView 内部的图像(ImageView 本身是 fill_parent / 填充整个屏幕)。我的想法是添加第二张图像(看起来像边框)并以与应该有边框的图像相同的方式翻译和缩放它,但这样做不是很方便。 有没有人更好的想法来实现这个目标?
【问题讨论】:
【参考方案1】:有两种方法可以实现这一点: 1) 为 imageView 添加填充并为其设置背景颜色。
final ImageView imageView = new ImageView(context);
imageView.setPadding(2*border,2*border,0,0);
final ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(width,height);
params.leftMargin = marginYouWouldSet + border;
params.topMargin = marginYouWouldSet + border;
imageView.setBackgroundDrawable(drawable);
imageView.setBackgroundColor(borderColor);
addView(imageView, params);
2) 另一种选择是覆盖视图的 draw 方法并在那里绘制边框:
@Override
protected void dispatchDraw(Canvas canvas)
borderDrawable.draw(canvas);
super.dispatchDraw(canvas);
...
public class BorderDrawable extends Drawable
private Rect mBounds;
private Paint mBorderPaint;
public BorderDrawable(Rect bounds, int thickness, int color)
mBounds = bounds;
mBorderPaint = new Paint();
mBorderPaint.setStrokeWidth(thickness);
mBorderPaint.setColor(color);
@Override
public void draw(Canvas canvas)
//left border
canvas.drawLine(
mBounds.left - thickness/2,
mBounds.top,
mBounds.left - thickness/2,
mBounds.bottom,
mBorderPaint);
//top border
canvas.drawLine(
mBounds.left,
mBounds.top - thickness/2,
mBounds.right,
mBounds.top - thickness/2,
mBorderPaint);
//right border
canvas.drawLine(
mBounds.right + thickness/2,
mBounds.top,
mBounds.right + thickness/2,
mBounds.bottom,
mBorderPaint);
//bottom border
canvas.drawLine(
mBounds.left,
mBounds.bottom + thickness/2,
mBounds.right,
mBounds.bottom + thickness/2,
mBorderPaint);
请注意,您要给出要绘制的行的中间(!)而且我还没有运行,也没有编译它,所以我不能 100% 确定它是正确的,但这些是方法: ) 矩形边界应该是视图的边界矩形 - (0,0,width,height)。
【讨论】:
【参考方案2】:或者,将 imageView 放在某种布局中并设置填充:
static class BorderView extends FrameLayout
public ImageView imageView;
public BorderView(Context context)
super(context);
setLayoutParams(//wrap content)
imageView = new ImageView(context);//set image and so forth
addView(imageView);
public void addSelectionBorder()
int border = 8;
setPadding(border,border,border,border);
setBackgroundColor(Color.BLUE);
public void removeSelectionBorder()
int border = 0;
setPadding(border,border,border,border);
setBackgroundColor(Color.BLACK);
【讨论】:
以上是关于Android 在 ImageView 中绘制边框的主要内容,如果未能解决你的问题,请参考以下文章
Xamarin Android 圆角边框与彩色 ImageView