介紹
- 調色板支持自定義工具選項。
- 調色板工具支持自定義端圈。
案例
代碼
import PencilKit
import UIKit
class ViewController: UIViewController {
lazy var canvasView: PKCanvasView = {
let canvasView = PKCanvasView()
canvasView.translatesAutoresizingMaskIntoConstraints = false
return canvasView
}()
// 調色板
lazy var toolPicker: PKToolPicker = {
// iOS18新增,自定義調色板工具選項
var config = PKToolPickerCustomItem.Configuration(identifier: "customTool", name: "pencil.and.scribble")
config.imageProvider = { toolItem in
guard let toolImage = UIImage(systemName: config.name) else {
return UIImage()
}
return toolImage
}
config.allowsColorSelection = true
config.defaultColor = .red
config.defaultWidth = 10.0
let customItem = PKToolPickerCustomItem(configuration: config)
// iOS18新增,自定義中間區(qū)域的調色板工具
let toolPicker = PKToolPicker(toolItems: [PKToolPickerInkingItem(type: .pen), PKToolPickerLassoItem(), PKToolPickerRulerItem(),
PKToolPickerEraserItem(type: .bitmap), PKToolPickerScribbleItem(), customItem])
return toolPicker
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(canvasView)
setToolPicker()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
NSLayoutConstraint.activate([
canvasView.topAnchor.constraint(equalTo: view.topAnchor),
canvasView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
canvasView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
canvasView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
}
// MARK: 為PKCanvasView設置PKToolPicker
func setToolPicker() {
toolPicker.addObserver(canvasView)
toolPicker.setVisible(true, forFirstResponder: canvasView)
// iOS18新增,自定義右側附加選項
toolPicker.accessoryItem = UIBarButtonItem(image: UIImage(systemName: "square.and.arrow.down.fill"), primaryAction: UIAction(handler: { [self] _ in
self.saveDrawing()
}))
canvasView.becomeFirstResponder()
}
// MARK: 保存繪畫內容到相冊
func saveDrawing() {
let drawing = canvasView.drawing
let image = drawing.image(from: canvasView.frame, scale: UIScreen.main.scale)
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
}
效果