如何为UIScrollview创建渐变背景以获取其内容

时间:2017-04-13 08:29:38

标签: ios uiscrollview

我想为UIScrollview创建渐变背景到其contentSize。我尝试使用下面的代码,但我没有得到我想要的东西。

- (void)drawRect:(CGRect)rect
{
    CGContextRef currentContext = UIGraphicsGetCurrentContext();

    CGGradientRef glossGradient;
    CGColorSpaceRef rgbColorspace;
    size_t num_locations = 2;
    CGFloat locations[2] = { 0.0, 1.0 };
    CGFloat components[8] = { 0.96, 0.97, 0.132, 1.000,  // Start color
    0.21, 0.20, 0.59, 1.000 }; // End color

    rgbColorspace = CGColorSpaceCreateDeviceRGB();
    glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);

    CGRect currentBounds = scroller.bounds;
    CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), 0.0f);
    CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMaxY(currentBounds));
    CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, midCenter, 0);

    CGGradientRelease(glossGradient);
    CGColorSpaceRelease(rgbColorspace);
}

有没有其他方法可以实现这一目标?

任何帮助表示赞赏!!

1 个答案:

答案 0 :(得分:0)

let gradient = CAGradientLayer()
let frame = CGRect(origin: CGPoint.zero, size: scrollView.contentSize)
gradient.frame = frame
gradient.colors = [UIColor.red.cgColor, UIColor.green.cgColor]
scrollView.layer.insertSublayer(gradient, at: 0)