一个可指定任意角为圆角的ImageView

这次带来一个继承ImageView控件,可以显示圆形,也可以显示圆角矩形,并且可以指定任意一个角为圆角。口说无凭,先来看一下效果吧。


                                         一个可指定任意角为圆角的ImageView_第1张图片


说起来这控件原本是在我刚学android的时候,为了实现圆形图片的效果在网上找,并且一直在用,后来在一个项目里有个图片

左上角和左下角是圆角,两外两个角不是圆角的设计,我就在这基础上改了一下,就是现在的这个控件。由于年代太久远加之我

改动得比较多,原博主的博客找不着了,非常抱歉。

 

又废话了一大堆,赶紧上源码吧。

 

首先控件支持直接在布局文件里设置属性,所以我们需要先自定义一些属性资源。在values文件夹下的attrs.xml文件(如果没有

就自己新建一个)里,添加如下代码:


    
    
    
    
    
    
    




    
    


    
    






然后就可以上控件本体了,控件名叫RoundImageView,如下:

RoundImageView.java:

public class RoundImageView extends ImageView {
    public static final int TYPE_CIRCLE = 0;
    public static final int TYPE_ROUND = 1;

    public static final int SCALE_TYPE_CROP = 0;
    public static final int SCALE_TYPE_FIT = 1;

    private static final int BODER_RADIUS_DEFAULT = 10;

    private static final String STATE_INSTANCE = "state_instance";
    private static final String STATE_TYPE = "state_type";
    private static final String STATE_BORDER_RADIUS = "state_border_radius";

    // 左上角是否为圆角
    private boolean corners_top_left = true;

    // 右上角是否为圆角
    private boolean corners_top_right = true;

    // 左下角是否为圆角
    private boolean corners_bottom_left = true;

    // 右下角是否为圆角
    private boolean corners_bottom_right = true;

    // 显示类型,可选项:圆形,圆角矩形
    private int type = TYPE_CIRCLE;

    // 填充类型,可选项:充满,剪裁
    private int scaleType = SCALE_TYPE_CROP;

    // 圆角半径
    private int borderRadius;

    private int width;
    private int radius;

    private Paint bitmapPaint;
    private RectF roundRect;
    private Matrix matrix;
    private BitmapShader bitmapShader;

    public RoundImageView(Context context) {
        this(context, null);
    }

    public RoundImageView(Context context, AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        matrix = new Matrix();
        bitmapPaint = new Paint();
        bitmapPaint.setAntiAlias(true);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RoundImageView);
        type = array.getInt(R.styleable.RoundImageView_type, TYPE_CIRCLE);
        scaleType = array.getInt(R.styleable.RoundImageView_scale, SCALE_TYPE_FIT);

        corners_top_left = array.getBoolean(R.styleable.RoundImageView_top_left, true);
        corners_top_right = array.getBoolean(R.styleable.RoundImageView_top_right, true);
        corners_bottom_left = array.getBoolean(R.styleable.RoundImageView_bottom_left, true);
        corners_bottom_right = array.getBoolean(R.styleable.RoundImageView_bottom_right, true);

        borderRadius = array.getDimensionPixelSize(R.styleable.RoundImageView_borderRadius,
                (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, BODER_RADIUS_DEFAULT,
                        getResources().getDisplayMetrics()));
        array.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (type == TYPE_CIRCLE) {
            width = Math.min(getMeasuredWidth(), getMeasuredHeight());
            radius = width / 2;
            setMeasuredDimension(width, width);
        }
    }

    /**
     * 显示图片
     */
    private void setUpShader() {
        Drawable drawable = getDrawable();
        if (drawable == null) {
            return;
        }
        Bitmap bitmap = drawableToBitamp(drawable);
        bitmapShader = new BitmapShader(bitmap, TileMode.CLAMP, TileMode.CLAMP);
        float scale = 1.0f;
        if (type == TYPE_CIRCLE) {
            scale = width * 1.0f / Math.min(bitmap.getWidth(), bitmap.getHeight());
            matrix.setScale(scale, scale);
        } else if (type == TYPE_ROUND) {
            float scaleWidth = getWidth() * 1.0f / bitmap.getWidth();
            float scaleHeight = getHeight() * 1.0f / bitmap.getHeight();
            scale = scaleWidth != scaleHeight ? Math.max(scaleWidth, scaleHeight) : 1f;
            if (scaleType == SCALE_TYPE_CROP) {
                matrix.setScale(scale, scale);
            } else if (scaleType == SCALE_TYPE_FIT) {
                matrix.setScale(scaleWidth, scaleHeight);
            }
        }
        bitmapShader.setLocalMatrix(matrix);
        bitmapPaint.setShader(bitmapShader);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (getDrawable() == null) {
            return;
        }
        setUpShader();

        // 圆角模式下剪裁相应的角
        if (type == TYPE_ROUND) {
            canvas.drawRoundRect(roundRect, borderRadius, borderRadius, bitmapPaint);
            if (!corners_top_left) {
                canvas.drawRect(0, 0, borderRadius, borderRadius, bitmapPaint);
            }
            if (!corners_top_right) {
                canvas.drawRect(roundRect.right - borderRadius, 0, roundRect.right, borderRadius, bitmapPaint);
            }
            if (!corners_bottom_left) {
                canvas.drawRect(0, roundRect.bottom - borderRadius, borderRadius, roundRect.bottom, bitmapPaint);
            }
            if (!corners_bottom_right) {
                canvas.drawRect(roundRect.right - borderRadius, roundRect.bottom - borderRadius, roundRect.right, roundRect.bottom, bitmapPaint);
            }
        } else {
            canvas.drawCircle(radius, radius, radius, bitmapPaint);
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (type == TYPE_ROUND) {
            roundRect = new RectF(0, 0, w, h);
        }
    }

    private Bitmap drawableToBitamp(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            BitmapDrawable bd = (BitmapDrawable) drawable;
            return bd.getBitmap();
        }
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();
        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        drawable.draw(canvas);
        return bitmap;
    }

    @Override
    protected Parcelable onSaveInstanceState() {
        Bundle bundle = new Bundle();
        bundle.putParcelable(STATE_INSTANCE, super.onSaveInstanceState());
        bundle.putInt(STATE_TYPE, type);
        bundle.putInt(STATE_BORDER_RADIUS, borderRadius);
        return bundle;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if (state instanceof Bundle) {
            Bundle bundle = (Bundle) state;
            super.onRestoreInstanceState(((Bundle) state).getParcelable(STATE_INSTANCE));
            this.type = bundle.getInt(STATE_TYPE);
            this.borderRadius = bundle.getInt(STATE_BORDER_RADIUS);
        } else {
            super.onRestoreInstanceState(state);
        }

    }

    /**
     * 设置圆角半径
     *
     * @param borderRadius 半径,单位dp
     */
    public void setBorderRadius(int borderRadius) {
        this.borderRadius = dp2px(borderRadius);
        invalidate();
    }

    /**
     * 设置填充类型
     *
     * @param scaleType 填充类型,可选项:SCALE_TYPE_CROP、SCALE_TYPE_FIT
     */
    public void setScaleType(int scaleType) {
        if (scaleType != SCALE_TYPE_CROP && scaleType != SCALE_TYPE_FIT) {
            return;
        }
        this.scaleType = scaleType;
        invalidate();
    }

    /**
     * 设置显示类型
     *
     * @param type 显示类型,可选项:TYPE_CIRCLE(圆形)、TYPE_ROUND(圆角)
     */
    public void setType(int type) {
        if (this.type != TYPE_ROUND && this.type != TYPE_CIRCLE) {
            return;
        }
        this.type = type;
        invalidate();
    }

    private int dp2px(int dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, getResources().getDisplayMetrics());
    }
}


上布局文件:

activity_main.xml:




    

    

    

    

    

    


用到的图片也放一下吧:

test.jpg:

一个可指定任意角为圆角的ImageView_第2张图片


主文件MainActivity里什么都没写,这里就不放了。

运行一下,就能看到开头所示的效果了。下面重点解释一下用法:


最简单的用法就像上面这样,引用一下控件什么都不用设置,此时显示为圆形,半径为长宽的较小者。


上述代码添加了type="round" 的属性,设置显示形状为圆角矩形,默认四个角全为圆角,圆角半径为10dp。


上述代码添加了app:scale="crop" 设置填充类型为crop,即视图的长宽与图片本身的长宽不一致时,保持原图比例,剪裁原图的一部分来显示,设置app:scale="fit"或不设置,则拉伸或压缩原图片来充满视图长宽。



上述代码添加了app:borderRadius="30dp"设置圆角半径为30dp,app:bottom_left="false"和app:bottom_right="false"表

示指定左下角和右下角不为圆角,其中,bottom_left表示左下角,bottom_right表示右下角,top_left表示左上角,top_right

表示右上角,不设置时默认全为true,需要指定某个角为圆角时只要将不需要为圆角的角对应的属性设置为false即可。

 

总的来说用法还是很简单的,希望对大家有用。


最后附上源码地址:点击打开链接

 

这次的内容就到这里,我们下次再见。











你可能感兴趣的:(自定义控件)