在 CGContext 中绘制 UIView

Draw UIView in CGContext

我正在尝试在 CGContext 中绘制简单的 UIView。 我正在正确绘制一个字符串,但未绘制 UIView

用于绘制视图的方法:

view.draw(view.layer, in: context)

但是不行。还有其他方法可以在 CGContext 中绘制 UIView 吗?

import UIKit
import CoreGraphics

let contextSize = CGSize(width: 400, height: 400)

UIGraphicsBeginImageContextWithOptions(contextSize, false, 0.0)

guard let context = UIGraphicsGetCurrentContext() else {
    fatalError("no context")
}

let size = CGSize(width: 30, height: 20)
let point = CGPoint(x: 20, y: 240)
let rect = CGRect(origin: point, size: size)

let text = "TEST"
let paragraphStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.minimumLineHeight = UIFont.systemFont(ofSize: 6).lineHeight
paragraphStyle.lineBreakMode = .byWordWrapping
paragraphStyle.alignment = .center
let attributes: [NSAttributedString.Key : Any] =  [.font: UIFont.systemFont(ofSize: 12),
                                                   .foregroundColor: UIColor.cyan,
                                                   .paragraphStyle: paragraphStyle]
text.draw(with: rect, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)


let view = UIView()
view.backgroundColor = .magenta
view.layer.borderWidth = 2.0
view.layer.borderColor = UIColor.green.cgColor
view.frame = CGRect(origin: point, size: size)

view.draw(view.layer, in: context)

let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

我相信你要找的是

view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)

这将绘制到您当前设置的任何上下文。这应该已经是你的背景,因为你 context = UIGraphicsGetCurrentContext()。我用你的代码试过了,它似乎有效。我得到了一张带有边框和一些文本的矩形图像。