我想在图像周围画一个边框。但我无法在ImageView本身对齐边框(就像它主要完成一样),因为我使用ImageMatrix翻译和缩放ImageView内部的图像(ImageView本身是fill_parent /填充整个屏幕)。我有想法添加第二张图片(看起来像边框)并翻译&以与应该有边框的图像相同的方式缩放它,但这样做并不是很方便。 有没有人更好地实现这个目标?
答案 0 :(得分:19)
有两种方法可以实现这一目标: 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)另一种选择是覆盖视图的绘制方法并绘制边框:
@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%确定它是正确的,但这些是方法: )Rect边界应该是视图的边界矩形 - (0,0,宽度,高度)。
答案 1 :(得分:0)
或者,将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);
}
}