source

Swift에서 단색으로 UIIMage 작성

gigabyte 2023. 4. 9. 21:33
반응형

Swift에서 단색으로 UIIMage 작성

단색으로 채워진 UIIMage를 프로그래밍 방식으로 만들고 싶습니다.스위프트에서 어떻게 하는지 아는 사람?

또 하나의 뛰어난 솔루션인 Swift 3.0

    public extension UIImage {
      convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
        let rect = CGRect(origin: .zero, size: size)
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
        color.setFill()
        UIRectFill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        guard let cgImage = image?.cgImage else { return nil }
        self.init(cgImage: cgImage)
      }
    }

Swift 2.2 호환성은 다음과 같이 UIImage에 다른 컨스트럭터를 작성하는 것입니다.

    public extension UIImage {
        public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
            let rect = CGRect(origin: .zero, size: size)
            UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
            color.setFill()
            UIRectFill(rect)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
        
            guard let cgImage = image?.CGImage else { return nil }
            self.init(CGImage: cgImage)
        }  
    }

이 방법으로 커스텀컬러 이미지를 작성할 수 있습니다.

    let redImage = UIImage(color: .redColor())

또는 필요에 따라 커스텀사이즈로 이미지를 만듭니다.

    let redImage200x200 = UIImage(color: .redColor(), size: CGSize(width: 200, height: 200))

Swift 4 버전:

extension UIColor {
    func image(_ size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
        return UIGraphicsImageRenderer(size: size).image { rendererContext in
            self.setFill()
            rendererContext.fill(CGRect(origin: .zero, size: size))
        }
    }
}

사용방법:

let image0 = UIColor.orange.image(CGSize(width: 128, height: 128))
let image1 = UIColor.yellow.image()

여기 또 다른 선택지가 있습니다.정확한 UIIMage 물체를 원하셨던 것 같은데요

func getImageWithColor(color: UIColor, size: CGSize) -> UIImage {
    let rect = CGRectMake(0, 0, size.width, size.height)
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    color.setFill()
    UIRectFill(rect)
    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}

Swift 코드에 삽입하여 호출합니다.

Swift 3.1:

func getImageWithColor(color: UIColor, size: CGSize) -> UIImage {
    let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    color.setFill()
    UIRectFill(rect)
    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return image
}

보다 깔끔한 접근방식은 로직을 내부로 캡슐화하는 것입니다.UIImage내선번호:

import UIKit

extension UIImage {
  class func imageWithColor(color: UIColor) -> UIImage {
    let rect: CGRect = CGRect(x: 0, y: 0, width: 1, height: 1)
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(1, 1), false, 0)
    color.setFill()
    UIRectFill(rect)
    let image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image!
  }
}

이제 소비자가 전화를 걸 수 있습니다.UIImage.imageWithColor(UIColor.blackColor())검은 배경의 이미지를 만듭니다.

@neoneeye의 뛰어난 응답에 약간의 변경을 가하여 발신자 코드를 CGSize를 작성할 필요가 없게 하고 다수의 다른 코드와 경합하지 않도록 이름을 변경했습니다.

스위프트 4

extension UIColor {
    func imageWithColor(width: Int, height: Int) -> UIImage {
        let size = CGSize(width: width, height: height)
        return UIGraphicsImageRenderer(size: size).image { rendererContext in
            self.setFill()
            rendererContext.fill(CGRect(origin: .zero, size: size))
        }
    }
}
class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        imageView.backgroundColor = UIColor.redColor()
    }
}

이미지를 직접 그리는 경우와 IBOutlet을 통해 연결하는 경우와 비슷한 방법입니다.

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        var frame = CGRectMake(100,100,100,100)
        var imageView2 = UIImageView(frame: frame)
        imageView2.backgroundColor = UIColor.redColor()
        self.view.addSubview(imageView2)
    }
}

세 번째 방법은 Anthonyliao에서 빌린 것입니다.조금 더 복잡함:

class ViewController: UIViewController {

    func getImageWithColor(color: UIColor, size: CGSize) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        color.setFill()
        UIRectFill(CGRectMake(0, 0, 100, 100))
        var image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var imageView = UIImageView(frame: CGRectMake(100,100,100,100))
        let screenImage = getImageWithColor(UIColor.redColor(), size: CGSize(width: 100, height: 100))
        imageView.image = screenImage
        self.view.addSubview(imageView)
    }
}

새로운 iOS 10 UIGraphics ImageRenderer API를 사용할 수 있습니다.

다음은 Swift 3.1의 UICollor에 대한 확장입니다.

extension UIColor {
func getImage(size: CGSize) -> UIImage {
    let renderer = UIGraphicsImageRenderer(size: size)
    return renderer.image(actions: { rendererContext in
        self.setFill()
        rendererContext.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
    })
}}

다음과 같은 계산된 속성을 갖는 것이 좋습니다.

extension UIColor {
    var imageRepresentation : UIImage {
      let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
      UIGraphicsBeginImageContext(rect.size)
      let context = UIGraphicsGetCurrentContext()

      context?.setFillColor(self.cgColor)
      context?.fill(rect)

      let image = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext()

    return image!
  }
}

사용방법:

let redImage = UIColor.red.imageRepresentation

Swift 3 버전의 @anthonyliao 수락 답변:

class func getImageWithColor(color: UIColor, size: CGSize) -> UIImage
{
    let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: size.width, height: size.height))
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    color.setFill()
    UIRectFill(rect)
    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return image
}

모서리가 둥근 직선

extension UIImage {
    convenience init?(color: UIColor) {
        let rect = CGRect(x: 0, y: 0, width: 10, height: 2)
        UIGraphicsBeginImageContextWithOptions(CGSize(width: 10, height: 2), false, 0)
        let bezierPath = UIBezierPath(roundedRect: rect, cornerRadius: 8)
        color.setFill()
        bezierPath.fill()
        let image = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        
        guard  let cgImage = image.cgImage else {
            return nil
        }
        self.init(cgImage: cgImage)
    }
}

Swift 5, Xcode 12.4 - UIImageView 솔루션

이 문제를 해결해야 한다면UIImageView예를 들어 다음과 같은 콤팩트한 솔루션을 선택할 수 있습니다.exampleImageView.fill()또는exampleImageView.fill(with: .black).

확장 코드:

extension UIImageView {
    func fill(with color: UIColor = .lightGray) {
        let size = self.bounds.size
        let image = UIGraphicsImageRenderer(size: size).image { rendererContext in
            color.setFill()
            rendererContext.fill(CGRect(origin: .zero, size: size))
        }
        self.image = image
    }
}

Swift 5 / 옵션 USIImage 사용 불가

  public static func withColor(_ color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
        let format = UIGraphicsImageRendererFormat()
        format.scale = 1
        let image =  UIGraphicsImageRenderer(size: size, format: format).image { rendererContext in
            color.setFill()
            rendererContext.fill(CGRect(origin: .zero, size: size))
        }
        return image
    }

필요할 경우 format.scale = 1을 사용하는 것을 잊지 마십시오.

UIGraphics ImageRenderer를 사용하여 UIImage를 만들거나 기존 CGContext 접근 방식을 사용할 수 있습니다. 아래는 주어진 색상으로 UIImage를 생성하는 편리성 초기화 기능입니다.

extension UIImage {
    /// create UIImage with color and given size
    convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1), alpha: CGFloat = 1, scale: CGFloat = 0) {
        if #available(tvOS 10.0, *) {
            let renderer = UIGraphicsImageRenderer(size: size)
            let image = renderer.image { (ctx) in
                let size = renderer.format.bounds.size
                ctx.fill(CGRect(origin: .zero, size: size))
                ctx.cgContext.setFillColor(color.cgColor)
            }
            guard let cgImage = image.cgImage else { return nil }
            self.init(cgImage: cgImage)
        } else {
            let rect = CGRect(origin: .zero, size: size)
            UIGraphicsBeginImageContextWithOptions(rect.size, false, scale)
            let context = UIGraphicsGetCurrentContext()!
            let fillColor = color.withAlphaComponent(alpha)
            context.setFillColor(fillColor.cgColor)
            context.fill(rect)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            guard let cgImage = image?.cgImage else { return nil }
            self.init(cgImage: cgImage)
        }
    }
}

사용하시는 애플리케이션이 iOS 10 이상을 지원하는 경우UIGraphicsImageRenderer 빠르니까.

다음은 정적 메서드/init 메서드입니다(옵션).UIImage)의 경우UIImage의 내선번호:

import UIKit

extension UIImage {
    static func from(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
        let format = UIGraphicsImageRendererFormat()
        format.scale = 1
        return UIGraphicsImageRenderer(size: size, format: format).image { context in
            color.setFill()
            context.fill(CGRect(origin: .zero, size: size))
        }
    }

    static func from(color: UIColor, size: CGFloat = 1) -> UIImage {
        return from(color: color, size: CGSize(width: size, height: size))
    }

    static func from(color: UIColor) -> UIImage {
        return from(color: color, size: 1)
    }

    convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
        let format = UIGraphicsImageRendererFormat()
        format.scale = 1
        let image = UIGraphicsImageRenderer(size: size, format: format).image { context in
            color.setFill()
            context.fill(CGRect(origin: .zero, size: size))
        }
        guard let cgImage = image.cgImage else { return nil }
        self.init(cgImage: cgImage)
    }

    convenience init?(color: UIColor, size: CGFloat = 1) {
        self.init(color: color, size: CGSize(width: size, height: size))
    }

    convenience init?(color: UIColor) {
        self.init(color: color, size: 1)
    }
}

struct Example {
    func createAnImageWithColorRed() {
        UIImage(color: .red, size: CGSize(width: 10, height: 10))
        UIImage(color: .red, size: 10)
        UIImage(color: .red)

        UIImage.from(color: .red, size: CGSize(width: 10, height: 10))
        UIImage.from(color: .red, size: 10)
        UIImage.from(color: .red)
    }
}

미리 보기:

여기에 이미지 설명 입력

언급URL : https://stackoverflow.com/questions/26542035/create-uiimage-with-solid-color-in-swift

반응형