iOS-色ごとに単色の画像を生成します

extension UIImage{
    
    
   static func imageWithColor(color:UIColor) -> UIImage?{
    
    
        let rect = CGRect.init(x:0, y:0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()!
        context.setFillColor(color.cgColor)
        context.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

使用する

   lazy var testView: UIImageView = {
    
    
        let imgView = UIImageView(frame: CGRect(x:100, y: 220, width:200, height: 200))
        imgView.backgroundColor = .white
        let image  = UIImage.imageWithColor(color: .red)
        imgView.image = image
        imgView.contentMode = .scaleToFill
        return imgView
    }()
  override func viewDidLoad() {
    
    
        super.viewDidLoad()
        view.backgroundColor = .brown
        view.addSubview(testView)
   }

効果図は次のとおりです。
ここに画像の説明を挿入

おすすめ

転載: blog.csdn.net/weixin_43259805/article/details/123271449