Android在ImageView中绘制边框

and*_*ert 6 android border imageview

我想在图像周围画一个边框.但我无法在ImageView本身对齐边框(就像它主要完成一样),因为我使用ImageMatrix翻译和缩放ImageView内部的图像(ImageView本身是fill_parent /填充整个屏幕).我有想法添加第二个图像(看起来像一个边框)并以与应该有边框的图像相同的方式平移和缩放它,但这样做并不是很方便.有没有人更好地实现这一目标?

ase*_*ovm 20

有两种方法可以实现这一点: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);
Run Code Online (Sandbox Code Playgroud)

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);
    }

}
Run Code Online (Sandbox Code Playgroud)

请注意,您要给出想要绘制的行的中间位置(!)而且我还没有运行,也没有编译它,所以我不是100%确定它是正确的,但这些是方法:) Rect bounds应该是视图的边界矩形 - (0,0,宽度,高度).