我想繪製一個漸變到UILabel,但它只繪製顏色,我看不到文字。 我看到的代碼從這裏StackOverflowiOS - 繪製漸變 - 斯威夫特
我的修改:
extension String{
func gradient(x:CGFloat,y:CGFloat, fontSize:CGFloat)->UIImage{
let font:UIFont = UIFont.systemFontOfSize(fontSize)
let name:String = NSFontAttributeName
let textSize: CGSize = self.sizeWithAttributes([name:font])
let width:CGFloat = textSize.width // max 1024 due to Core Graphics limitations
let height:CGFloat = textSize.height // max 1024 due to Core Graphics limitations
UIGraphicsBeginImageContext(CGSizeMake(width, height))
let context = UIGraphicsGetCurrentContext()
UIGraphicsPushContext(context!)
//draw gradient
let glossGradient:CGGradientRef?
let rgbColorspace:CGColorSpaceRef?
let num_locations:size_t = 2
let locations:[CGFloat] = [ 0.0, 1.0 ]
let components:[CGFloat] = [(202/255.0), (197/255.0), (52/255.0), 1.0, // Start color
(253/255.0), (248/255.0), (101/255.0), 1.0] // End color
rgbColorspace = CGColorSpaceCreateDeviceRGB()
glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations)
let topCenter = CGPointMake(0, 0);
let bottomCenter = CGPointMake(0, textSize.height);
CGContextDrawLinearGradient(context, glossGradient, topCenter, bottomCenter, CGGradientDrawingOptions.DrawsBeforeStartLocation)
UIGraphicsPopContext()
let gradientImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return gradientImage
}
}
和的ImageView的
self.timeLeftIV = UIImageView(frame: CGRectMake(self.pyramidFakeView.frame.origin.x/2-25,0, 100,20))
self.timeLeftIV.image = "59:48".gradient(timeLeftIV.frame.origin.x, y: timeLeftIV.frame.origin.y, fontSize: 6.0)
你的代碼不起作用 –
@VivekSehrawat看到swift 3.0更新 – beyowulf
: - 看起來像這樣當我在操場上測試時。 https://drive.google.com/open?id=0B62pT4Le2is4UkhSTGlLQUhBWXM –