2009-11-08 59 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