Forum Xamarin.Forms

Custom renderer to rounded view only in one side

CaioshinCaioshin ITMember ✭✭

Hello,
I currently developed a custom renderer to realize a rounded view with antialias that works good (the code of the renderer is here below), using a bitmap as mask over a canvas.
My problem is that now I need to round only 1 border of my view but I'm unable to achieve it.

Can somebody point me in the right direction to fill my border where I need?

class ContentViewWithRoundCornersRenderer : VisualElementRenderer<ContentView>
{
    private float _cornerRadius;
    private RectF _bounds;
    private Path _path;
    Bitmap _offscreenBitmap;
    Canvas _offscreenCanvas;

    protected override void OnElementChanged(ElementChangedEventArgs<ContentView> e)
    {
        base.OnElementChanged(e);

        if (e.OldElement != null)
        {
            return;
        }

        var element = (ContentViewWithRoundCorners)Element;

        _cornerRadius = TypedValue.ApplyDimension(ComplexUnitType.Dip, element.CornerRadius,
            Context.Resources.DisplayMetrics);

        paint = new Paint(PaintFlags.AntiAlias);

        maskPaint = new Paint(PaintFlags.AntiAlias | PaintFlags.FilterBitmap);
        maskPaint.SetXfermode(new PorterDuffXfermode(PorterDuff.Mode.Clear));

    }


    protected override void OnSizeChanged(int w, int h, int oldw, int oldh)
    {
        base.OnSizeChanged(w, h, oldw, oldh);
        if (w != oldw && h != oldh)
        {
            _bounds = new RectF(0, 0, w, h);
        }
    }

    private Bitmap maskBitmap;
    private Paint paint, maskPaint;
    public override void Draw(Canvas canvas)
    {
        if(_offscreenBitmap==null)
            _offscreenBitmap = Bitmap.CreateBitmap(canvas.Width, canvas.Height, Bitmap.Config.Argb8888);

        if(_offscreenCanvas==null)
            _offscreenCanvas = new Canvas(_offscreenBitmap);

        base.Draw(_offscreenCanvas);

        if (maskBitmap == null)
            maskBitmap = createMask(canvas.Width, canvas.Height);

        _offscreenCanvas.DrawBitmap(maskBitmap, 0f, 0f, maskPaint);
        canvas.DrawBitmap(_offscreenBitmap, 0f, 0f, paint);
    }

    private Bitmap createMask(int width, int height)
    {
        Bitmap _mask = Bitmap.CreateBitmap(width, height, Bitmap.Config.Alpha8);
        Canvas _canvas = new Canvas(_mask);
        Paint _paint = new Paint(PaintFlags.AntiAlias);

        _canvas.DrawRect(0, 0, width, height, _paint);

        _paint.SetXfermode(new PorterDuffXfermode(PorterDuff.Mode.Clear));
        _canvas.DrawRoundRect(_bounds, _cornerRadius, _cornerRadius, _paint);

        return _mask;
    }

}

Sign In or Register to comment.