美文网首页
Swift 绘制图片与文字

Swift 绘制图片与文字

作者: 艾欧尼亚 | 来源:发表于2019-04-03 15:50 被阅读0次

1.加载图片

func loadImage() {
        let urlStr = "https://ssl-media.720static.com/@/115400/2/14568975829362493.png"
        var requeset = URLRequest.init(url: URL.init(string: urlStr)!)//Origin
        requeset.setValue("https://720yun.com", forHTTPHeaderField: "Origin")
        requeset.setValue("https://720yun.com", forHTTPHeaderField: "Referer")

        URLSession.shared.dataTask(with: requeset) { (datas, response, error) in
            guard error == nil else {
                return
            }
            guard let data = datas else {
                return
            }
            guard let image = UIImage.init(data: data) else {
                return
            }
            guard let contextImg = self.creataImage(image: image) else  {
                return
            }
            DispatchQueue.main.async {
                self.imageV.image = image
                self.imageView.image = contextImg
            }
        }.resume()
    }

2.绘制新图片

func creataImage(image: UIImage) -> UIImage? { // -> UIImage?
        let width = image.size.width
        let height = image.size.height + 20
        // 开启上下文
        UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), false, UIScreen.main.scale)
        
        // 获得上下文
        guard let context = UIGraphicsGetCurrentContext() else {return nil}
        context.setFillColor(UIColor.blue.cgColor)
        // 填充背景色
        context.fill(CGRect(x: 0, y: 0, width: width, height: height))
        // 画图片
        image.draw(at: CGPoint(x: 0, y: 0))
        // 画文字
        let attr = [NSAttributedString.Key.foregroundColor: UIColor.white.withAlphaComponent(0.3),NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15)]
        let text = "共产主义接班人"
        (text as NSString).draw(at: CGPoint(x: 0, y: height - 20), withAttributes: attr)
        
        let endImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return endImage
    }

3.将view转成image

func imageWithView(view: UIView) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.main.scale)
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        let snapshotImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return snapshotImage
    }

相关文章

网友评论

      本文标题:Swift 绘制图片与文字

      本文链接:https://www.haomeiwen.com/subject/hrszbqtx.html