2014-02-19 28 views
0

我使用的代碼稍加修改的版本,我從上面的答案在這裏抓住不工作:Modern technique of adding gradient to UIView梯度α的drawRect中

我修改後的代碼:

- (void)drawRect:(CGRect)rect 
{ 
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 

    // The if statements are surely a crappy way of setting the locations, but whatever 
    CGGradientRef gradient; 
    if ([self.colors count] == 3) { 
     CGFloat gradientLocations[] = {0, 0.5, 1}; 
     gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)self.colors, gradientLocations); 
    } else { 
     CGFloat gradientLocations[] = {0, 1}; 
     gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)self.colors, gradientLocations); 
    } 

    CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect)); 
    CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));  

    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0); 
} 

我已經將它放入一個類稱爲Gradient_View,我試圖將其子類化。在我的子類的init方法,我有這樣的:

self.colors = [NSArray arrayWithObjects: 
      (id)[UIColor colorWithRed:1.0f green:1.0f blue:1.0f alpha:1.0f].CGColor, 
      [UIColor colorWithRed:1.0f green:1.0f blue:1.0f alpha:0.0f].CGColor, 
       nil]; 

注意,在最後一個數組第二顏色具有的alpha值爲0,所以梯度應該成爲看穿。但是,結果我在模擬器得到的是完全不透明:

enter image description here

我怎樣才能得到透明度的工作?

回答

4

檢查並查看您的UIView是否不透明。確保不透明設置爲NO。

+0

這很容易:) – maxedison

+0

我已經被超過一次:) –