UIView border with fade or blur effect

前端 未结 5 1652
悲哀的现实
悲哀的现实 2020-12-13 03:17

I\'m looking for method to add gradually fading or maybe blured border (I don\'t exactly know how to name this effect) to arbitrary UIView. I don\'t need animated effect, I

5条回答
  •  清歌不尽
    2020-12-13 03:38

    Here's iKiR and Mazyod's answer, translated to Xamarin.iOS (Monotouch). Note that there's no need to draw rectangles before and after the gradient if you just pass the right flags to the the DrawLinearGradient method:

    var vl = myView.Layer;
    var l = new CALayer ();
    l.Frame = new RectangleF(vl.Frame.Width/2, vl.Frame.Height/2,
                vl.Frame.Width, vl.Frame.Height) ;
    var cs = CGColorSpace.CreateDeviceRGB ();
    var g = new CGBitmapContext (null, 
                (int) vl.Bounds.Size.Width, (int)vl.Bounds.Size.Height, 
                8, 0, cs, CGImageAlphaInfo.PremultipliedLast);
    var colors = new CGColor[] { UIColor.FromWhiteAlpha(1, 0).CGColor, 
                UIColor.FromWhiteAlpha(1, 1f).CGColor };
    var grad = new CGGradient (cs, colors, new float[] { 0f, 1f });
    int gradH = 20, gradHPos = 0;
    g.DrawLinearGradient (grad, 
                new PointF (l.Frame.Width / 2, gradHPos), new PointF (l.Frame.Width / 2, gradHPos + gradH), 
                CGGradientDrawingOptions.DrawsBeforeStartLocation | CGGradientDrawingOptions.DrawsAfterEndLocation);
    grad.Dispose ();
    
    l.Contents = g.ToImage ();
    g.Dispose ();
    
    vl.Mask = l;
    vl.MasksToBounds = true;
    

提交回复
热议问题