您的位置:首页 > 其它

创建一个简单的圆角ImageView

2016-02-22 17:41 267 查看
需求:创建一个简单的圆角ImageView,使左上角,右上角的边缘变成圆角.

public class CornerImageView extends ImageView {
int radius = 10;//圆角半径
float density = getResources().getDisplayMetrics().density;//屏幕密度
public CornerImageView(Context context) {
super(context);
}

public CornerImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}

public CornerImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}

//重写onDraw方法
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getLayoutParams().width;
int height = getLayoutParams().height;
//创建矩形区域
RectF oval = new RectF();
oval.left = 0 - radius;
oval.top = 0 - radius;
oval.bottom = oval.top + radius * 2;
oval.right = oval.left + radius * 2;
//创建画笔
Paint paint = new Paint();

paint.setStrokeWidth(0.5f * density);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.parseColor("#F6F6F6"));

canvas.drawLine(0.5f, 0, 0.5f, height, paint);//左侧竖线
canvas.drawLine(width - 0.5f, 0, width - 0.5f, height, paint);//右侧竖线
canvas.drawLine(0, 0.5f, width, 0.5f, paint);//顶部横线
canvas.drawLine(0, height, width, height, paint);//底部横线

paint.setColor(Color.WHITE);
//绘制左上角圆角.颜色为白色.
for (; oval.left < 0; ) {
oval.left += 0.1;
oval.top += 0.1;
oval.bottom += 0.1;
oval.right += 0.1;
canvas.drawArc(oval, 180, 90, false, paint);
}
//最后一根弧线为灰色
paint.setColor(Color.parseColor("#F6F6F6"));
canvas.drawArc(oval, 180, 90, false, paint);
//重设矩形区域为ImageView右上角,中心点为矩形右上角
oval.left = width - radius;
oval.top = 0 - radius;
oval.right = oval.left + radius * 2;
oval.bottom = oval.top + radius * 2;
paint.setColor(Color.WHITE);
//绘制右上角弧形区域.
for (; oval.right > width; ) {
oval.left -= 0.1;
oval.top += 0.1;
oval.bottom += 0.1;
oval.right -= 0.1;
canvas.drawArc(oval, -90, 90, false, paint);
}
//绘制最后一根弧线
paint.setColor(Color.parseColor("#F6F6F6"));
canvas.drawArc(oval, -90, 90, false, paint);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: