How do I add a radial gradient to a UIView?

后端 未结 5 1868
你的背包
你的背包 2020-12-14 21:12

I have a UIView which I want to have a radial gradient, and I\'m wondering how to go about doing this?

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 21:43

    Here's Karlis answer in c# for Xamarin.iOS. Here I am specifying the colors directly but you can of course implement it the same way Karlis did.

    public class RadialView : UIView
    {
        public RadialView(CGRect rect) : base (rect)
        {
            this.BackgroundColor = UIColor.DarkGray;
        }
    
        public override void Draw(CGRect rect)
        {
            CGColor[] colorComponents = { UIColor.DarkGray.CGColor, UIColor.LightGray.CGColor };
            var locations = new nfloat[]{ 1, 0 }; 
            var radius = this.Bounds.Size.Height / 2;
            CGPoint center = new CGPoint(this.Bounds.Size.Width / 2, this.Bounds.Size.Height / 2);
    
            var context = UIGraphics.GetCurrentContext();
            context.SaveState();
            var colorSpace = CGColorSpace.CreateDeviceRGB();
    
            CGGradient gradient = new CGGradient(colorSpace, colorComponents, locations);
            context.DrawRadialGradient(gradient, center, 0, center, radius, CGGradientDrawingOptions.None);
    
            context.RestoreState();
            colorSpace.Dispose();
            gradient.Dispose();
        }
    }
    

提交回复
热议问题