在iOS开发中,CGContext
是 Core Graphics 框架中的一个关键组件,用于在图形上下文中进行低级别的绘图操作。UIView
是 iOS 用户界面框架 UIKit 中的一个基础类,用于显示内容和处理用户交互。在 UIView
的 draw(_:)
方法中,你可以获取到一个 CGContext
对象,然后在这个上下文中进行自定义绘图。
draw(_:)
方法: 在自定义的 UIView
子类中重写 draw(_:)
方法。draw(_:)
方法中通过 UIGraphicsGetCurrentContext()
获取当前的图形上下文。import UIKit
class CustomView: UIView {
override func draw(_ rect: CGRect) {
// 获取当前的图形上下文
guard let context = UIGraphicsGetCurrentContext() else { return }
// 设置绘图属性
context.setStrokeColor(UIColor.blue.cgColor)
context.setLineWidth(5.0)
// 绘制一条线
let startPoint = CGPoint(x: rect.minX, y: rect.midY)
let endPoint = CGPoint(x: rect.maxX, y: rect.midY)
context.move(to: startPoint)
context.addLine(to: endPoint)
context.strokePath()
// 绘制文本
let text = "Hello, CGContext!"
let attributes: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: 20),
.foregroundColor: UIColor.red
]
let textSize = text.size(withAttributes: attributes)
let textRect = CGRect(x: (rect.width - textSize.width) / 2,
y: (rect.height - textSize.height) / 2,
width: textSize.width,
height: textSize.height)
text.draw(in: textRect, withAttributes: attributes)
}
}
CGContext
中绘制可能比使用多个子视图更高效。CGContext
中绘制动画帧。draw(_:)
方法被调用,通常是因为视图没有被正确添加到视图层次结构中。draw(_:)
方法中进行耗时操作,尽量复用图形资源。通过上述步骤和示例代码,你可以在 UIView
中使用 CGContext
进行自定义绘图。这种方法适用于需要精细控制视图外观的场景。
领取专属 10元无门槛券
手把手带您无忧上云