可能的重复: 在iPhone应用程序中手动绘制渐变?
我的应用程序需要在UIView或UILabel中显示文本,但背景必须是一个梯度,而不是一个真正的UIColor。使用图形程序来创建理想的外观是不好的,因为文本可能会根据服务器返回的数据而变化。
有人知道最快的解决方法吗? 非常感谢你的意见。
可能的重复: 在iPhone应用程序中手动绘制渐变?
我的应用程序需要在UIView或UILabel中显示文本,但背景必须是一个梯度,而不是一个真正的UIColor。使用图形程序来创建理想的外观是不好的,因为文本可能会根据服务器返回的数据而变化。
有人知道最快的解决方法吗? 非常感谢你的意见。
当前回答
您还可以使用一个像素宽的图形图像作为渐变,并设置view属性来展开图形以填充视图(假设您考虑的是简单的线性渐变,而不是某种径向图形)。
其他回答
您可以使用核心图形来绘制梯度,正如在Mike的响应中指出的那样。作为一个更详细的例子,你可以创建一个UIView子类来作为你的UILabel的背景。在UIView子类中,重写drawRect:方法并插入类似于下面的代码:
- (void)drawRect:(CGRect)rect
{
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGGradientRef glossGradient;
CGColorSpaceRef rgbColorspace;
size_t num_locations = 2;
CGFloat locations[2] = { 0.0, 1.0 };
CGFloat components[8] = { 1.0, 1.0, 1.0, 0.35, // Start color
1.0, 1.0, 1.0, 0.06 }; // End color
rgbColorspace = CGColorSpaceCreateDeviceRGB();
glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);
CGRect currentBounds = self.bounds;
CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), 0.0f);
CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMidY(currentBounds));
CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, midCenter, 0);
CGGradientRelease(glossGradient);
CGColorSpaceRelease(rgbColorspace);
}
这个特殊的例子创建了一个白色,光滑风格的渐变,从UIView的顶部绘制到它的垂直中心。你可以设置UIView的backgroundColor为任何你喜欢的颜色,这个光泽会被画在那个颜色上面。你也可以使用CGContextDrawRadialGradient函数绘制径向梯度。
你只需要适当地调整这个UIView的大小,并添加你的UILabel作为它的子视图来获得你想要的效果。
编辑(4/23/2009):根据St3fan的建议,我已经在代码中用它的边界替换了视图的帧。这纠正了视图的原点不是(0,0)的情况。
您还可以使用一个像素宽的图形图像作为渐变,并设置view属性来展开图形以填充视图(假设您考虑的是简单的线性渐变,而不是某种径向图形)。
这就是我得到的工作-设置UIButton在xCode的IB透明/清除,没有bg图像。
UIColor *pinkDarkOp = [UIColor colorWithRed:0.9f green:0.53f blue:0.69f alpha:1.0];
UIColor *pinkLightOp = [UIColor colorWithRed:0.79f green:0.45f blue:0.57f alpha:1.0];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = [[shareWordButton layer] bounds];
gradient.cornerRadius = 7;
gradient.colors = [NSArray arrayWithObjects:
(id)pinkDarkOp.CGColor,
(id)pinkLightOp.CGColor,
nil];
gradient.locations = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:0.0f],
[NSNumber numberWithFloat:0.7],
nil];
[[recordButton layer] insertSublayer:gradient atIndex:0];
我知道这是一个较老的帖子,但作为将来的参考:
在iPhone SDK 3.0,自定义渐变可以很容易地实现,不需要子类化或图像,通过使用新的CAGradientLayer:
UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)] autorelease];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[view.layer insertSublayer:gradient atIndex:0];
看看CAGradientLayer文档。您可以选择指定起始点和结束点(如果您不希望从顶部到底部直接进行线性渐变),甚至可以指定映射到每种颜色的特定位置。
我通过UIImageView的子视图实现了这个。ImageView指向的图像是一个渐变。然后我在UIView中设置背景色,我就有了一个彩色渐变视图。接下来我使用我需要的视图,我画的所有东西都将在这个渐变视图下。通过在ImageView的顶部添加第二个视图,您可以有一些选项,您的绘图将低于或高于梯度…