develop

Text Gradation 텍스트에 그라데이션 추가 본문

iOS

Text Gradation 텍스트에 그라데이션 추가

pikachu987 2020. 12. 29. 23:02
반응형

func makeLabel() -> UILabel? {
    let label = UILabel()
    label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
    label.text = "Hello World!"

    let textSize = (label.text ?? "").size(withAttributes: [NSAttributedString.Key.font : label.font])

    let tempLabel =  UILabel(frame: CGRect(x: 0, y: 0, width: textSize.width, height: .greatestFiniteMagnitude))
    tempLabel.numberOfLines = 0
    tempLabel.text = label.text
    tempLabel.font = label.font
    tempLabel.sizeToFit()
    let height = tempLabel.frame.height

    guard let image = self.image(CGSize(width: tempLabel.frame.width, height: height)) else { return nil }

    label.textColor = UIColor(patternImage: image)

    return label
}

func image(_ size: CGSize) -> UIImage? {
    UIGraphicsBeginImageContext(size)
    defer { UIGraphicsEndImageContext() }
    guard let context = UIGraphicsGetCurrentContext() else { return nil }
    UIGraphicsPushContext(context)

    guard let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: [UIColor.red.cgColor, UIColor.black.cgColor] as CFArray, locations: nil) else { return nil }
    context.drawLinearGradient(gradient, start: CGPoint(x: 0, y: size.height), end: CGPoint(x: size.width, y: size.height), options: [])

    UIGraphicsPopContext()
    return UIGraphicsGetImageFromCurrentImageContext()
}

 

더 자세한 코드는 https://github.com/pikachu987/TextGradation 참조.

반응형

'iOS' 카테고리의 다른 글

IBDesignable, IBInspectable  (0) 2020.12.30
Image Face Detector 사진에서 얼굴 찾기  (0) 2020.12.30
PHAsset  (0) 2020.12.29
Preview (PDF, EXCEL)  (0) 2020.12.28
UDID UUID ADID  (0) 2020.12.27
Comments