iPhone上的UIView和UILabels上的渐变

可能重复:
在iPhone应用程序中手动绘制渐变?

我的应用程序需要在UIViewUILabel显示文本,但背景必须是渐变而不是真正的UIColor 。 使用图形程序创建所需的外观并不好,因为文本可能因服务器返回的数据而异。

有没有人知道解决这个问题的最快方法? 你的想法非常感谢。


您也可以使用一个像素宽的图形图像作为渐变,并将视图属性设置为展开图形以填充视图(假设您正在考虑简单线性渐变而不是某种径向图形)。


我意识到这是一个较旧的主题,但供将来参考:

从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文档。 您可以选择指定开始点和结束点(以防您不希望从顶部到底部直线渐变)或甚至映射到每种颜色的特定位置。


您可以使用Core Graphics绘制渐变,如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的顶部绘制到它的垂直中心。 你可以设置UIViewbackgroundColor为你喜欢的任何东西,并且这种光泽将被绘制在该颜色之上。 您还可以使用CGContextDrawRadialGradient函数绘制径向渐变。

你只需要适当地调整这个UIView大小并添加你的UILabel作为它的子视图来获得你想要的效果。

编辑(2009年4月23日):根据St3fan的建议,我用代码中的边界代替了视图的框架。 这可以纠正视图的原点不是(0,0)的情况。

链接地址: http://www.djcxy.com/p/95799.html

上一篇: Gradients on UIView and UILabels On iPhone

下一篇: Launch an app from within another (iPhone)