創建一個簡單的圓角ImageView

需求:創建一個簡單的圓角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);

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章