角落里的渐变

时间:2014-09-16 13:28:00

标签: ios uiview gradient

我想创建一个右上角和左下角渐变的背景视图 我如何实现这一目标?

我有这段代码

  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];

但它没有做我想要的,我不知道如何让它做我想做的。

目前的结果: enter image description here

期望的结果是:

enter image description here

2 个答案:

答案 0 :(得分:5)

这应该可以解决问题:

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];

您必须阅读有关CAGradientLayer

的文档

答案 1 :(得分:0)

我能想到的最好的是绘制两个径向渐变并填充其余部分。请注意,如果其中任何一个应该(部分)透明,则需要进行一些调整。

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

}