ios - 在 iOS 中的白色上绘制透明到白色的渐变

标签 ios transparency drawrect linear-gradients cagradientlayer

我有一个 iOS 应用程序,在主屏幕上滚动显示文本。我希望文本在屏幕底部淡出。所以我制作了一个自定义 View ,并在 drawRect 中做了类似的事情:

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = UIGraphicsGetCurrentContext();

CGFloat gradLocs[] = {0, 1};
CGColor *color1 = [UIColor clearColor].CGColor;
CGColor *color2 = [UIColor whiteColor].CGColor;
CFArrayRef arr = (CFArrayRef)@[(id)color1, (id)color2];
CGGradientRef grad = CGGradientCreateWithColors(colorSpace, arr, gradLocs);

CGContextSaveGState(context);
CGContextDrawLinearGradient(context, grad, CGPointMake(0, 0), CGPointMake(0, rect.size.height), 0);
CGContextRestoreGState(context);

基本上,在 View 上绘制一个从透明到白色的线性渐变。我也尝试过使用 CAGradientLayer 来做到这一点:

CAGradientLayer *layer = [CAGradientLayer layer];
layer.colors = @[(id)[UIColor clearColor].CGColor, (id)[UIColor whiteColor].CGColor];
layer.locations = @[@(0), @(1)];
layer.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
[self.layer insertSublayer:layer atIndex:0];

无论哪种方式,如果它被绘制在白色之上,我就会变成灰色。 PaintCode显示相同的东西:

PaintCode screenshot

这是为什么?似乎渐变不应该在白色之上完全可见。

最佳答案

+[UIColor clearColor] 实际上是透明的黑色。因为你想要透明的白色,你应该使用:

color1 = [[UIColor whiteColor] colorWithAlphaComponent:0.0].CGColor;

仔细阅读 +[UIColor clearColor] 的文档,它说它将返回灰度和 alpha 值 0.0 的颜色。所以从白色到透明的渐变中间是 [UIColor initWithWhite:0.5 alpha:0.5],即透明灰色。

关于ios - 在 iOS 中的白色上绘制透明到白色的渐变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28303348/

相关文章:

ios - Appboy SDK iOS,unreadCardCountForCategories 委托(delegate)不提供更新卡的计数

ios - didDeselectRowAtIndexPath 未被调用

python - 如何使用标准化标记透明度创建散点图

ios - TableView didSelectRowAtIndexPath,仅在选择第二次单击后有效

ios - 使用 AVFoundation 叠加两个视频

html - 映射图像的不透明部分

html - css3 border-image的透明png问题

ios - 如何优化drawRect?

ios - 如何将 UIScrollView 的转换应用于 UIView?

iphone - 在 iOS 中绘制部分图像的最有效方法