Я пытаюсь нарисовать градиент для UILabel, но он рисует только цвета, которые я не вижу в тексте. Я видел код здесь StackOverflowiOS - Градиент рисования - Swift
моя модификация:
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 –