[swift] 킹피셔를 사용하여 이미지 다운로드 중에 이미지에 캡션을 추가하는 방법은?

킹피셔(Kingfisher)는 Swift에서 이미지 다운로드와 캐싱을 처리하는 라이브러리입니다. 이미지에 캡션을 추가하기 위해서는 킹피셔의 커스텀 프로세서를 사용할 수 있습니다.

먼저 킹피셔를 프로젝트에 설치해야 합니다. 프로젝트의 Podfile에 아래의 내용을 추가하고, 터미널에서 pod install 명령을 실행합니다.

pod 'Kingfisher'

설치가 완료되면, 다음과 같은 코드를 사용하여 이미지에 캡션을 추가할 수 있습니다.

import UIKit
import Kingfisher

class ViewController: UIViewController {
    @IBOutlet weak var imageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let caption = "This is a caption"
        let imageUrl = URL(string: "https://example.com/image.jpg")
        
        let processor = OverlayImageProcessor(overlay: caption, font: UIFont.systemFont(ofSize: 18), textColor: .white, backgroundColor: .black)
        
        imageView.kf.setImage(with: imageUrl, options: [.processor(processor)])
    }
}

struct OverlayImageProcessor: ImageProcessor {
    let overlay: String
    let font: UIFont
    let textColor: UIColor
    let backgroundColor: UIColor
    
    func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
        guard let image = item.image else { return nil }
        
        UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
        defer { UIGraphicsEndImageContext() }
        
        image.draw(at: .zero)
        
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = .center
        
        let attributes: [NSAttributedString.Key: Any] = [
            .font: font,
            .foregroundColor: textColor,
            .backgroundColor: backgroundColor,
            .paragraphStyle: paragraphStyle
        ]
        
        let textRect = CGRect(x: 0, y: image.size.height - font.lineHeight - 10, width: image.size.width, height: font.lineHeight + 10)
        
        overlay.draw(in: textRect, withAttributes: attributes)
        
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

위의 코드에서 OverlayImageProcessor는 이미지를 프로세싱하여 이미지에 캡션을 추가하는 역할을 담당합니다. overlay 속성에는 추가할 캡션의 내용을 입력하고, font, textColor, backgroundColor 속성을 원하는대로 설정할 수 있습니다.

ViewControllerviewDidLoad 함수에서는 imageView에 이미지를 로드하고, 옵션으로 processor를 설정하여 캡션을 추가할 수 있습니다.

이렇게 하면 킹피셔를 사용하여 이미지 다운로드 중에 이미지에 캡션을 추가할 수 있습니다.

참고: Kingfisher GitHub 페이지