Round cornered ImageView supporting background color in Android?

依然范特西╮ 提交于 2019-12-08 21:07:42

Rounded corners can be done using Lollipop's outlines and pre-Lollipop paths. See:

  1. Prepare masks

    if (cornerRadius > 0) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setClipToOutline(true);
            setOutlineProvider(ShadowShape.viewOutlineProvider);
        } else {
            cornersMask = new Path();
            cornersMask.addRoundRect(new RectF(0, 0, getWidth(), getHeight()), cornerRadius, cornerRadius, Path.Direction.CW);
            cornersMask.setFillType(Path.FillType.INVERSE_WINDING);
        }
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            setOutlineProvider(ViewOutlineProvider.BOUNDS);
    }
    
  2. draw(Canvas) method

    if (cornerRadius > 0 && getWidth() > 0 && getHeight() > 0 && Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT_WATCH) {
        int saveFlags = Canvas.MATRIX_SAVE_FLAG | Canvas.CLIP_SAVE_FLAG | Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG;
        int saveCount = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, saveFlags);
    
        super.draw(canvas);
    
        paint.setXfermode(pdMode);
        canvas.drawPath(cornersMask, paint);
    
        canvas.restoreToCount(saveCount);
        paint.setXfermode(null);
    } else {
        super.draw(canvas);
    }
    
  3. and the missing viewOutlineProvider

        viewOutlineProvider = new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
                ShadowShape shadowShape = ((ShadowView) view).getShadowShape();
                if (shadowShape == RECT) {
                    outline.setRect(0, 0, view.getWidth(), view.getHeight());
                } else if (shadowShape == ROUND_RECT) {
                    outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), ((CornerView) view).getCornerRadius());
                } else if (shadowShape == CIRCLE) {
                    outline.setOval(0, 0, view.getWidth(), view.getHeight());
                }
            }
        };
    

And the image:

You can mess with this code in any way you want. You can cut the image and the background to any shape, separately or together. For more details check out the code on github.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!