[swift] AlamofireImage를 사용하여 이미지에 텍스트 그리기

AlamofireImage는 Swift에서 이미지 다운로드 및 캐싱을 처리하는 라이브러리입니다. 이 라이브러리를 사용하면 웹에서 이미지를 가져와 UIImageView에 표시할 수 있습니다.

하지만 때로는 이미지에 특정 텍스트를 추가하고 싶을 수도 있습니다. 이러한 경우에는 이미지를 다운로드한 후에 텍스트를 그리는 작업을 수행해야 합니다. 이번 블로그 포스트에서는 AlamofireImage와 Core Graphics를 사용하여 이미지에 텍스트를 그리는 방법을 알아보겠습니다.

필요한 준비물

이미지 다운로드 및 텍스트 그리기

먼저, AlamofireImage를 사용하여 이미지를 다운로드합니다. 해당 이미지를 UIImageView에 표시하고 싶다면, 다음과 같이 코드를 작성할 수 있습니다.

import AlamofireImage

let imageURL = "https://example.com/image.jpg"

let imageView = UIImageView()

if let url = URL(string: imageURL) {
    imageView.af.setImage(withURL: url)
}

다음으로는 Core Graphics를 사용하여 이미지에 텍스트를 그릴 준비를 해야 합니다. 다음의 함수를 추가하고 이미지에 텍스트를 그리는 작업을 수행합니다.

import UIKit

func drawTextOnImage(image: UIImage, text: String) -> UIImage? {
    let textColor = UIColor.white
    let textFont = UIFont(name: "Helvetica Bold", size: 30)!
    
    let scale = UIScreen.main.scale
    UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
    
    let textFontAttributes = [
        NSAttributedString.Key.font: textFont,
        NSAttributedString.Key.foregroundColor: textColor,
    ] as [NSAttributedString.Key : Any]
    
    image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
    
    let rect = CGRect(
        x: 0,
        y: image.size.height - 100,
        width: image.size.width,
        height: 100
    )
    
    text.draw(in: rect, withAttributes: textFontAttributes)
    
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    
    return newImage
}

이제 이미지를 다운받으면 해당 이미지에 텍스트를 그리는 작업을 진행할 수 있습니다. 다음과 같이 코드를 작성하여 이미지에 텍스트를 그려봅시다.

if let url = URL(string: imageURL) {
    imageView.af.setImage(withURL: url) { response in
        if let image = response.value {
            let newTextImage = drawTextOnImage(image: image, text: "Hello, World!")
            imageView.image = newTextImage
        }
    }
}

이제 이미지를 다운로드하고 텍스트를 그린 후, 화면에 표시될 것입니다.

결론

AlamofireImage와 Core Graphics를 사용하여 이미지에 텍스트를 그리는 방법을 살펴보았습니다. 이를 통해 웹에서 이미지를 가져와 텍스트를 추가하는 작업을 간단하게 수행할 수 있습니다.