我正在使用此处描述的方法为 vanillaUIView
实例设置渐变背景,而无需创建子类。然而,视图完全是黑色的。这是我的代码:
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 315.0f, 44.0f)];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, 315.0, 44.0f, 8, 4 * 315, colorSpace, kCGImageAlphaNoneSkipFirst);
// Colors only for debugging purposes
CGColorRef startColor = (__bridge CGColorRef)[UIColor greenColor];
CGColorRef endColor = (__bridge CGColorRef)[UIColor redColor];
CFMutableArrayRef colors = CFArrayCreateMutable(kCFAllocatorDefault, 2, &kCFTypeArrayCallBacks);
CFArrayAppendValue(colors, startColor);
CFArrayAppendValue(colors, endColor);
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, colors, (const CGFloat []){0.25f, 0.75f});
CGContextDrawLinearGradient(context, gradient, CGPointZero, CGPointMake(0.0f, 44.0f), 0);
CGImageRef cgImage = CGBitmapContextCreateImage(context);
UIImage *backgroundGradient = [UIImage imageWithCGImage:cgImage];
[view setBackgroundColor:[UIColor colorWithPatternImage:backgroundGradient]];
CFRelease(colors);
CGGradientRelease(gradient);
CGImageRelease(cgImage);
CGColorSpaceRelease(colorSpace);
CGContextRelease(context);
return view;
我相信上下文分配可能有问题,因为创建的图像返回所需大小(315x44)。我错过了什么?我还能检查什么可以帮助我调试这个问题?