Подтвердить что ты не робот

Как добавить радиальный градиент в UIView?

У меня есть UIView, который я хочу иметь радиальный градиент, и мне интересно, как это сделать?

4b9b3361

Ответ 1

Для этого вам нужно перейти к Core Graphics и использовать CGContextDrawRadialGradient.

Подобные вопросы

Как рисовать сектор с радиальным градиентом (iphone)

Как нарисовать линию градиента (затухание в/из) с помощью Core Graphics/iPhone?

Другие ресурсы

В этом учебнике показано, как рисовать иконки с градиентами на iOS здесь:

http://redartisan.com/2011/05/13/porting-iconapp-core-graphics

Он поставил код в Github, в комплекте с подклассом UIView, который показывает (довольно длинный) способ создания градиентов с использованием Core Graphics:

https://github.com/crafterm/IconApp/blob/master/IconApp/IconView.m

Ответ 2

Первый подкласс a UIView:

@implementation UIRadialView

- (void)drawRect:(CGRect)rect
{
    // Setup view
    CGFloat colorComponents[] = {0.0, 0.0, 0.0, 1.0,   // First color:  R, G, B, ALPHA (currently opaque black)
                                 0.0, 0.0, 0.0, 0.0};  // Second color: R, G, B, ALPHA (currently transparent black)
    CGFloat locations[] = {0, 1}; // {0, 1) -> from center to outer edges, {1, 0} -> from outer edges to center
    CGFloat radius = MIN((self.bounds.size.height / 2), (self.bounds.size.width / 2));
    CGPoint center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2);

    // Prepare a context and create a color space
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    // Create gradient object from our color space, color components and locations
    CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, colorComponents, locations, 2);

    // Draw a gradient
    CGContextDrawRadialGradient(context, gradient, center, 0.0, center, radius, 0);
    CGContextRestoreGState(context);

    // Release objects
    CGColorSpaceRelease(colorSpace);
    CGGradientRelease(gradient);
}

@end

И затем добавьте его в свое представление:

UIRadialView *radialView = [[UIRadialView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
radialView.backgroundColor = [UIColor redColor];
[self.view addSubview:radialView];

Результат:

Радиальный градиентный вид

Ответ 3

Swift 3 - @IBDesignable

Я работал с Карлисом и Александром. Я стремился максимально упростить. Например, удаление цветового пространства и местоположений (nil), поэтому градиент использует значения по умолчанию.

Как использовать

Шаг 1

Создайте файл и добавьте этот код:   import UIKit

@IBDesignable
class RadialGradientView: UIView {

    @IBInspectable var InsideColor: UIColor = UIColor.clear
    @IBInspectable var OutsideColor: UIColor = UIColor.clear

    override func draw(_ rect: CGRect) {
        let colors = [InsideColor.cgColor, OutsideColor.cgColor] as CFArray
        let endRadius = min(frame.width, frame.height) / 2
        let center = CGPoint(x: bounds.size.width / 2, y: bounds.size.height / 2)
        let gradient = CGGradient(colorsSpace: nil, colors: colors, locations: nil)
        UIGraphicsGetCurrentContext()!.drawRadialGradient(gradient!, startCenter: center, startRadius: 0.0, endCenter: center, endRadius: endRadius, options: CGGradientDrawingOptions.drawsBeforeStartLocation)
    }
}

Шаг 2

На раскадровке установите UIView выше RadialGradientView в Identity Inspector: Пользовательский класс

Шаг 3

Задайте внутренний цвет и внешний цвет для вашего градиента в инспекторе атрибутов и посмотрите изменения на вашей раскадровке: Радиальный градиент

(Примечание: я сделал UIView на раскадровке достаточно большим, чтобы он заполнил весь

Ответ 4

Здесь ответ Карлиса в Swift 3:

override func draw(_ rect: CGRect) {

    // Setup view
    let colors = [UIColor.white.cgColor, UIColor.black.cgColor] as CFArray
    let locations = [ 0.0, 1.0 ] as [CGFloat]
    let radius = min((self.bounds.size.height / 2), (self.bounds.size.width / 2))
    let center = CGPoint.init(x: self.bounds.size.width / 2, y: self.bounds.size.height / 2)

    // Prepare a context and create a color space
    let context = UIGraphicsGetCurrentContext()
    context!.saveGState()
    let colorSpace = CGColorSpaceCreateDeviceRGB()

    // Create gradient object from our color space, color components and locations
    let gradient = CGGradient.init(colorsSpace: colorSpace, colors: colors, locations: locations)

    // Draw a gradient
    context!.drawRadialGradient(gradient!, startCenter: center, startRadius: 0.0, endCenter: center, endRadius: radius, options: CGGradientDrawingOptions(rawValue: 0))
    context?.restoreGState()
}

Ответ 5

Здесь Карлис отвечает в С# для Xamarin.iOS. Здесь я указываю цвета напрямую, но вы можете, конечно, реализовать его так же, как это сделал Карлис.

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();
    }
}