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 關注
- 1119 瀏覽
添加回答
舉報