Lena Bru
Lena Bru

Reputation: 13947

Gradient in corner

I want to create a background view that has top right corner and bottom left corner gradients How do I achieve this ?

I have this code

  CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = self.bounds;
    gradient.colors = [NSArray arrayWithObjects: (id)[[UIColor whiteColor] CGColor],(id)[[UIColor blackColor] CGColor], nil];
    gradient.startPoint = CGPointZero;
    [self.layer insertSublayer:gradient atIndex:0];

but it doesnt do what i want, and I don't know how to make it do what I want.

current result: enter image description here

The desired result is:

enter image description here

Upvotes: 3

Views: 2273

Answers (2)

David Berry
David Berry

Reputation: 41246

The best I could come up with was to draw two radial gradients and fill the rest. Note that this will need some adjustment if any of this should be (partially) transparent.

func + (origin:CGPoint, offset:CGSize) -> CGPoint {
    return CGPoint(x: origin.x + offset.width, y: origin.y + offset.height)
}

class GradientView : UIView {

    override func drawRect(rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()
        CGContextSaveGState(context)

        let topLeft = CGPoint(x: 0, y: 0)
        let bottomRight = self.bounds.origin + self.bounds.size

        let colors = [
            UIColor.purpleColor(),
            UIColor.redColor(),
            UIColor.redColor()
            ].map { $0.CGColor as AnyObject! }
        let points : [CGFloat] = [0.0, 0.75, 1.0]
        let gradient = CGGradientCreateWithColors(nil, colors, points)

        CGContextSetFillColorWithColor(context, UIColor.redColor().CGColor)
        CGContextFillRect(context, self.bounds)
        CGContextDrawRadialGradient(context, gradient, topLeft, 0, topLeft, self.bounds.size.width, 0)
        CGContextDrawRadialGradient(context, gradient, bottomRight, 0, bottomRight, self.bounds.size.width, 0)

        CGContextRestoreGState(context)
    }

}

Upvotes: 1

Larme
Larme

Reputation: 26096

This should do the trick:

CAGradientLayer *gradient = [CAGradientLayer layer];
[gradient setFrame:[self bounds]];

//Pink color to set with your needs
UIColor *pinkColor = [UIColor colorWithRed:1 green:105/255.0 blue:180/255.0 alpha:1];
gradient.colors = @[(id)[pinkColor CGColor],
                    (id)[[UIColor whiteColor] CGColor],
                    (id)[[UIColor whiteColor] CGColor],
                    (id)[pinkColor CGColor]];

//You may have to change these values to your needs.
[gradient setLocations:@[@(0.0), @(0.2), @(0.8), @(1.0)]];

//From Upper Right to Bottom Left
[gradient setStartPoint:CGPointMake(1, 0)];
[gradient setEndPoint:CGPointMake(0, 1)];

//Apply
[[self layer] insertSublayer:gradient atIndex:0];

You have to read the documentation about CAGradientLayer.

Upvotes: 5

Related Questions