【问题标题】:Gradient alpha not working in drawRect渐变 alpha 在 drawRect 中不起作用
【发布时间】:2014-02-19 23:07:10
【问题描述】:

我正在使用我从这里的最佳答案中获取的稍微修改过的代码版本:Modern technique of adding gradient to UIView

我修改后的代码:

- (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,因此渐变应该是透明的。但是,我在模拟器中得到的结果是完全不透明的:

如何让透明度发挥作用?

【问题讨论】:

    标签: ios objective-c gradient drawrect


    【解决方案1】:

    检查您的 UIView 是否不透明。确保 opaque 设置为 NO。

    【讨论】:

    • 我不止一次被它击中 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    • 2017-11-12
    相关资源
    最近更新 更多