ios iPhone 上 UIView 和 UILabels 上的渐变

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/422066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:30:44  来源:igfitidea点击:

Gradients on UIView and UILabels On iPhone

iphoneioscocoa-touchgradient

提问by TonyNeallon

Possible Duplicate:
Manually drawing a gradient in iPhone apps?

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

My application needs to display text in either a UIViewor UILabelbut the back ground must be a gradient as opposed to a true UIColor. Using a graphics program to create desired look is no good as the text may vary depending on data returned from a server.

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

Does anyone know the quickest way to tackle this? Your thoughts are greatly appreciated.

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

采纳答案by Kendall Helmstetter Gelner

You could also use a graphic image one pixel wide as the gradient, and set the view property to expand the graphic to fill the view (assuming you are thinking of a simple linear gradient and not some kind of radial graphic).

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

回答by Mirko Froehlich

I realize this is an older thread, but for future reference:

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

As of iPhone SDK 3.0, custom gradients can be implemented very easily, without subclassing or images, by using the new CAGradientLayer:

从 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];

Take a look at the CAGradientLayer docs. You can optionally specify start and end points (in case you don't want a linear gradient that goes straight from the top to the bottom), or even specific locations that map to each of the colors.

查看 CAGradientLayer 文档。您可以选择指定起点和终点(以防您不想要从顶部到底部的线性渐变),或者甚至是映射到每种颜色的特定位置。

回答by Brad Larson

You can use Core Graphics to draw the gradient, as pointed to in Mike's response. As a more detailed example, you could create a UIViewsubclass to use as a background for your UILabel. In that UIViewsubclass, override the drawRect:method and insert code similar to the following:

您可以使用 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); 
}

This particular example creates a white, glossy-style gradient that is drawn from the top of the UIViewto its vertical center. You can set the UIView's backgroundColorto whatever you like and this gloss will be drawn on top of that color. You can also draw a radial gradient using the CGContextDrawRadialGradientfunction.

此特定示例创建了从 顶部UIView到其垂直中心绘制的白色光泽样式渐变。您可以将UIView's设置为backgroundColor您喜欢的任何值,并且此光泽将绘制在该颜色之上。您还可以使用该CGContextDrawRadialGradient函数绘制径向渐变。

You just need to size this UIViewappropriately and add your UILabelas a subview of it to get the effect you desire.

您只需要UIView适当地调整大小并将您的添加UILabel为它的子视图即可获得您想要的效果。

EDIT (4/23/2009): Per St3fan's suggestion, I have replaced the view's frame with its bounds in the code. This corrects for the case when the view's origin is not (0,0).

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

回答by ThomasW

Note:The results below apply to older versions of iOS, but when testing on iOS 13 the stepping doesn't occur. I don't know for which version of iOS the stepping was removed.

注意:下面的结果适用于旧版本的 iOS,但在 iOS 13 上测试时不会发生步进。我不知道为哪个版本的 iOS 删除了步进。



When using CAGradientLayer, as opposed to CGGradient, the gradient is not smooth, but has noticeable stepping to it. See this example:

CAGradientLayer与 相比CGGradient,使用 时,渐变并不平滑,但有明显的步进。见这个例子

To get more attractive results it is better to use CGGradient.

为了获得更有吸引力的结果,最好使用CGGradient.

回答by Robert Wagstaff

Mirko Froehlich's answer worked for me, except when i wanted to use custom colors. The trick is to specify UI color with Hue, saturation and brightness instead of RGB.

Mirko Froehlich 的回答对我有用,除非我想使用自定义颜色。诀窍是用色调、饱和度和亮度而不是 RGB 来指定 UI 颜色。

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = myView.bounds;
UIColor *startColour = [UIColor colorWithHue:.580555 saturation:0.31 brightness:0.90 alpha:1.0];
UIColor *endColour = [UIColor colorWithHue:.58333 saturation:0.50 brightness:0.62 alpha:1.0];
gradient.colors = [NSArray arrayWithObjects:(id)[startColour CGColor], (id)[endColour CGColor], nil];
[myView.layer insertSublayer:gradient atIndex:0];

To get the Hue, Saturation and Brightness of a color, use the in built xcode color picker and go to the HSB tab. Hue is measured in degrees in this view, so divide the value by 360 to get the value you will want to enter in code.

要获得颜色的色相、饱和度和亮度,请使用内置的 xcode 颜色选择器并转到 HSB 选项卡。在此视图中,色调以度为单位,因此将值除以 360 以获得您要在代码中输入的值。

回答by Anna Billstrom

This is what I got working- set UIButton in xCode's IB to transparent/clear, and no bg image.

这就是我在 xCode 的 IB 中将 UIButton 设置为透明/清晰的,并且没有 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];

回答by mahboudz

I achieve this in a view with a subview that is an UIImageView. The image the ImageView is pointing to is a gradient. Then I set a background color in the UIView, and I have a colored gradient view. Next I use the view as I need to and everything I draw will be under this gradient view. By adding a second view on top of the ImageView, you can have some options whether your drawing will be below or above the gradient...

我在一个带有 UIImageView 子视图的视图中实现了这一点。ImageView 指向的图像是一个渐变。然后我在 UIView 中设置了背景颜色,并且我有一个彩色渐变视图。接下来,我根据需要使用视图,我绘制的所有内容都将在此渐变视图下。通过在 ImageView 顶部添加第二个视图,您可以选择您的绘图是在渐变之下还是之上......