【问题标题】:Drawing a gradient as view's background without subclassing绘制渐变作为视图的背景而不进行子类化
【发布时间】:2012-06-03 21:33:13
【问题描述】:

我正在使用方法described here 为香草UIView 实例设置渐变背景而不创建子类。然而,视图完全是黑色的。这是我的代码:

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)。我错过了什么?还有什么可以帮助我调试这个问题的检查?

【问题讨论】:

  • 为什么不想创建子类?

标签: ios cocoa-touch core-graphics


【解决方案1】:

这不是你获得CGColorRef 的方式

[UIColor redColor].CGColor

【讨论】:

  • 这是另一个问题 - 我在这些行上遇到了崩溃(使用 ARC)。不知道为什么。
  • 你不需要这个演员表(__bridge CGColorRef)。另请在此处查看潜在 ARC 问题的答案stackoverflow.com/questions/8155844/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-04
  • 2022-09-29
  • 2022-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多