3 回答
TA贡献1883条经验 获得超3个赞
Brad Larson和Bach都提供了非常有用的答案。第二个对我有用,但是需要预先显示图像。我想要更具动态性的东西,所以我将两种解决方案结合在一起:
在UIImage上绘制所需的渐变
使用UIImage设置颜色图案
结果有效,在下面的屏幕截图中,您也可以看到一些希腊字符也很好地渲染。(我还在渐变顶部添加了笔触和阴影)
iOS风格化UILabel,大棕狐狸
这是我标签的自定义init方法,以及在UIImage上呈现渐变的方法(我从博客文章中获得的该功能的部分代码,现在找不到它可以引用它):
- (id)initWithFrame:(CGRect)frame text:(NSString *)aText {
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor clearColor];
self.text = aText;
self.textColor = [UIColor colorWithPatternImage:[self gradientImage]];
}
return self;
}
- (UIImage *)gradientImage
{
CGSize textSize = [self.text sizeWithFont:self.font];
CGFloat width = textSize.width; // max 1024 due to Core Graphics limitations
CGFloat height = textSize.height; // max 1024 due to Core Graphics limitations
// create a new bitmap image context
UIGraphicsBeginImageContext(CGSizeMake(width, height));
// get context
CGContextRef context = UIGraphicsGetCurrentContext();
// push context to make it current (need to do this manually because we are not drawing in a UIView)
UIGraphicsPushContext(context);
//draw gradient
CGGradientRef glossGradient;
CGColorSpaceRef rgbColorspace;
size_t num_locations = 2;
CGFloat locations[2] = { 0.0, 1.0 };
CGFloat components[8] = { 0.0, 1.0, 1.0, 1.0, // Start color
1.0, 1.0, 0.0, 1.0 }; // End color
rgbColorspace = CGColorSpaceCreateDeviceRGB();
glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);
CGPoint topCenter = CGPointMake(0, 0);
CGPoint bottomCenter = CGPointMake(0, textSize.height);
CGContextDrawLinearGradient(context, glossGradient, topCenter, bottomCenter, 0);
CGGradientRelease(glossGradient);
CGColorSpaceRelease(rgbColorspace);
// pop context
UIGraphicsPopContext();
// get a UIImage from the image context
UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
// clean up drawing environment
UIGraphicsEndImageContext();
return gradientImage;
}
我将尝试完成该UILabel子类并将其发布。
TA贡献1946条经验 获得超3个赞
我在寻找解决方案,而DotSlashSlash的答案中隐藏了一个答案!
为了完整起见,答案和最简单的解决方案是:
UIImage *myGradient = [UIImage imageNamed:@"textGradient.png"];
myLabel.textColor = [UIColor colorWithPatternImage:myGradient];
- 3 回答
- 0 关注
- 1064 浏览
添加回答
举报