android ImageView 添加边框

有两种方法可以给ImageView添加边框,一种是通过xml文件配置shape.另一种是重写ImageView的ondraw方法,这里用第二中方法:

package org.example.image.widgets;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.widget.ImageView;

public class MyImageView extends ImageView {

	// 边框颜色
	private int borderColor;
	// 边框宽度
	private int borderWidth;

	public MyImageView(Context context) {
		super(context);
	}

	// 设置边框颜色
	public void setBorderColor(int borderColor) {
		this.borderColor = borderColor;
	}

	// 设置边框宽度
	public void setBorderWidth(int borderWidth) {
		this.borderWidth = borderWidth;
	}

	// 重写绘图方法
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		// 画边框
		Rect rect = canvas.getClipBounds();
		rect.bottom--;
		rect.right--;
		Paint paint = new Paint();
		paint.setColor(borderColor);
		paint.setStyle(Paint.Style.STROKE);
		paint.setStrokeWidth(borderWidth);
		canvas.drawRect(rect, paint);
	}

}


你可能感兴趣的:(android ImageView 添加边框)