我想创建一个具有渐变背景的应用程序,随着人们在屏幕上上下滑动而变化。我希望渐变是径向类型的,这就是为什么我使用 Core Graphics 而不是CAGradientLayer
.
我的视图控制器有一个子类的属性,UIView
它的drawRect具有以下实现:
- (void)drawRect:(CGRect) rect
{
self.alpha = 1.0;
// Draw radial gradient here using C language
CGPoint startCenter, endCenter;
startCenter = CGPointMake(CGRectGetMidX(rect), CGRectGetHeight(rect));
endCenter = CGPointMake(CGRectGetMidX(rect), CGRectGetHeight(rect));
//radial gradient radius;
CGFloat startRadius = 0.17 * CGRectGetHeight(rect);
CGFloat endRadius = 1.04 * CGRectGetHeight(rect);
//gradient locations.
CGFloat locations[2] = {0.0, 0.8};
//gradient color components.
CGFloat components[8] = {
232/255.0, 249/255.0, 229/255.0, 1.0,
133/255.0, 174/255.0, 127/255.0, 1.0,
};
//Drawing code.
CGContextRef context = UIGraphicsGetCurrentContext();
//Get RGB color space
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
//create gradient.
CGGradientRef gradient = CGGradientCreateWithColorComponents(space, components, locations, 2);
CGColorSpaceRelease(space);
//draw gradient.
CGContextDrawRadialGradient(context, gradient, startCenter, startRadius,endCenter,endRadius, kCGGradientDrawsBeforeStartLocation);
_contextToSave = UIGraphicsGetCurrentContext(); // useless
CGGradientRelease(gradient);
我想要的是能够更新渐变,所以我正在考虑在我的组件CGFloat
数组中使用属性或实例变量,然后为更改设置动画,但我不知道该怎么做。
我知道我应该等待手势识别器并根据手势调整渐变,但由于我的问题不是何时更新而是如何更新,我决定尝试在我的方法中更新viewDidAppear
渐变ViewController
没啥事儿。
只是为了尝试创建渐变和动画的变化,我在以下代码中尝试了以下viewDidAppear
代码ViewController
:
[UIView animateWithDuration:6.0 animations:^{
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat colorsComponents[8] = {
145/255.0, 149/255.0, 229/255.0, 1.0,
133/255.0, 74/255.0, 27/255.0, 1.0,
};
CGFloat locations[2] = {0.0, 0.8};
//CGContextRef context = UIGraphicsGetCurrentContext();
CGPoint startCenter, endCenter;
startCenter = CGPointMake(0.5 * gradientView.frame.size.width, gradientView.frame.size.height);
startCenter = endCenter;
CGFloat startRadius = 0.17 * gradientView.frame.size.height;
CGFloat endRadius = 1.04 * gradientView.frame.size.height;
CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, colorsComponents, locations, 2);
CGContextDrawRadialGradient(_subclassofView.contextToSave, gradient, startCenter, startRadius, endCenter, endRadius, kCGGradientDrawsBeforeStartLocation);
}];
感谢您的帮助。