# 4.2 图形的绘制


<br>


<br>

# Canvas 的使用

Canvas 字面意思就是“画布”，在这个画布上可以绘制各种图形。与 Shape 不同的是，Canvas 支持即时绘制，比如用户可以使用手指在屏幕上涂鸦。

Canvas 的构建非常简单：

```swift
Canvas { context, size in
  // draw
}
```

- context：GraphicsContext 类型，用于绘图的上下文。
- size：画布尺寸。

[GraphicsContext](https://developer.apple.com/documentation/swiftui/graphicscontext) 支持多种绘制操作，比如文字（Text）、图片（Image）、路径（Path）等，它还可以给绘制的内容添加蒙版（Mask）、滤镜（Filter）等效果，还能对绘图上下文进行多种变换操作（Transform）、设置混合模式（Blend）等，更详细的用法请参考文档。

示例中演示了使用 Canvas 绘制文本、图片、路径，注释写的非常详细，这里就不再细说。

<span style="background: #007BFF; color: white; padding: 3px 10px; border-radius: 5px">> 查看示例</span>

笔者还使用 Canvas 实现了一个简易的涂鸦画板程序，有兴趣的读者请参考：[DrawingBoard](https://github.com/zzzwco/DrawingBoard)。

# 样式与行为

在前面的章节中，已经穿插着介绍过一些关于图形样式的设置，比如 tint、border、foregroundStyle、blur 、内外（inner/drop）阴影效果以及 Materials 等。以下仅介绍之前没有涉及到的内容，由于篇幅有限难以面面俱到，关于图形绘制的详细内容请参考 [Drawing and graphics](https://developer.apple.com/documentation/swiftui/drawing-and-graphics) 。

## 更多的渐变效果

前面已经介绍和使用过 [ShapeStyle](https://developer.apple.com/documentation/swiftui/shapestyle) 中的线性渐变（LinearGradient），示例中新增了 RadialGradient 和 AngularGradient 的使用效果。

## 颜色的变换

颜色可以进行高亮、反色、饱和度等多种变换操作，官方示例图文并茂，请参考文档：

- [brightness(_:)](https://developer.apple.com/documentation/swiftui/view/brightness(_:))
- [contrast(_:)](https://developer.apple.com/documentation/swiftui/view/contrast(_:))
- [colorInvert()](https://developer.apple.com/documentation/swiftui/view/colorinvert())
- [colorMultiply(_:)](https://developer.apple.com/documentation/swiftui/view/colormultiply(_:))
- [saturation(_:)](https://developer.apple.com/documentation/swiftui/view/saturation(_:))
- [grayscale(_:)](https://developer.apple.com/documentation/swiftui/view/grayscale(_:))
- [hueRotation(_:)](https://developer.apple.com/documentation/swiftui/view/huerotation(_:))
- [luminanceToAlpha()](https://developer.apple.com/documentation/swiftui/view/luminancetoalpha())

## 视图的变换

视图支持多种变换操作，一些常规的缩放操作比如 scaleToFill、scaleToFit、scaleEffect 使用比较简单就没有例举，示例中演示了对视图进行 2D 和 3D 旋转。

## 蒙板与裁剪

[mask(alignment:_:)](https://developer.apple.com/documentation/swiftui/view/mask(alignment:_:)) 可以为视图添加蒙版，比如示例中使用 Text 作为图片的蒙版，可以生成具有镂空效果的文字。

[clipped(antialiased:)](https://developer.apple.com/documentation/swiftui/view/clipped(antialiased:)) 和 [clipShape(_:style:)](https://developer.apple.com/documentation/swiftui/view/clipshape(_:style:)) 可以裁剪视图。

## 视图合成

[blendMode(_:)](https://developer.apple.com/documentation/swiftui/view/blendmode(_:)) 可以将视图重叠部分以特定的模式进行混合，示例仅演示了一部分混合效果。

[compositingGroup()](https://developer.apple.com/documentation/swiftui/view/compositinggroup()) 可以将一组视图合成为一个视图组，然后将整个视图组当成一个整体对其设置样式。如示例所示：

```swift
ZStack {
  Capsule()
    .fill(.yellow)
    .frame(width: 150, height: 60)
  Text("Hello")
    .font(.largeTitle)
    .bold()
}
.compositingGroup()
.shadow(color: .red, radius: 3)
```

如果不使用 compositingGroup，shadow 会分别对胶囊形状和文本生效。而使用 compositingGroup 后，shadow 是对合成后的视图组生效的。类似这种需要防止子视图使用容器的修饰器方法的场景，compositingGroup 非常有用，在它后面调用的修饰器方法，生效的其实是合成后的整个视图组。

[drawingGroup()](https://developer.apple.com/documentation/swiftui/view/drawinggroup(opaque:colormode:)) 可以借助 [Metal](https://developer.apple.com/documentation/metal) 优化性能。示例中的花朵，由于需要绘制的子视图过多，在执行动画时有明显的卡顿，而使用 drawingGroup 后：

```swift
if drawingGroup {
  flower
    .drawingGroup()
} else {
  flower
}
```

动画变得非常流畅，这得益于 drawingGroup，它将 flower 所有的视图内容交给 Metal 处理，由 GPU 进行更快速的图形计算，最后合成一个位图，然后渲染在屏幕上。

如果在绘制复杂视图时遇到性能问题，drawingGroup 将会非常有用。



---

> 作者: 宋明  
> URL: https://apolla.cc/posts/swiftui-eul/4.2-%E5%9B%BE%E5%BD%A2%E7%9A%84%E7%BB%98%E5%88%B6/  

