2009-11-08 58 views
0

我正在尝试做一些应该很简单的事情。我想为我的某个视图添加渐变。我可以将它添加到self.view,但不能添加到viewWithGradient。这里是代码:iPhone Layer confusion

CAGradientLayer *gradient = [CAGradientLayer layer]; 

UIColor *colorFirst  = [UIColor colorWithWhite:0.10 alpha:0.15]; 
UIColor *colorLast = [UIColor colorWithWhite:0.535 alpha:0.8]; 
NSArray *colors = [NSArray arrayWithObjects:(id)colorFirst.CGColor, colorLast.CGColor, nil]; 
gradient.colors = colors; 

NSNumber *stopFirst = [NSNumber numberWithFloat:0.00]; 
NSNumber *stopLast = [NSNumber numberWithFloat:1.00]; 
NSArray *locations = [NSArray arrayWithObjects:stopFirst, stopLast, nil]; 
gradient.locations = locations; 
gradient.frame = CGRectMake(0.0, viewWithGradient.frame.origin.y, viewWithGradient.frame.size.width, height_of_gradient); 

[self.view.layer addSublayer:gradient]; // this works. I get a nice gradient at 
        // the bottom of the view, where I want it, 
        // but I need the gradient further down in 
        // my view hierarchy. 
// [viewWithGradient.layer addSublayer:gradient]; // this doesn't. There 
        // is no visually noticeable change 
        // if this is uncommented and the 
        // above line is. 

viewWithGradient是在我的主视图内viewController(self.view)内的一个小视图。这个viewWithGradient只有一个其他视图。这是一个UILabel,它只占用了视野面积的一半左右。它具有透明背景,但标签以白色绘制其文本。我需要在UILabel下面使用渐变,而不是在self.view上使用UILabel。

我目前怀疑我的框架/边界可能会将渐变放在屏幕外。有人看到我失踪的任何东西吗?这似乎是CALayer最简单的用法,而且我花了太多时间。

+0

你有没有尝试用viewWithGradient的背景颜色弄糟。也许改变viewWithGradient的不透明属性为NO? ......只是一些闪过的建议。 – wkw 2009-11-09 00:00:07

+0

其不透明已设置为NO,背景设置为clearColor。我很难过。 – mahboudz 2009-11-09 02:37:42

回答

0

渐变的框架的y坐标是viewWithGradient.frame.origin.y。你真的想要0吗?如果viewWithGradient超过屏幕一半,您的渐变将画出屏幕。

+0

是的!我实际上是在垂直于viewWithGradient的同一点。我忘记了,因为我将该图层添加到该视图中,框架必须与该视图相关,而不是整个屏幕。谢谢! – mahboudz 2009-11-09 05:30:02