🎨
SwiftUIのCanvas基本8選(線、塗り、字、画像)
- 線(3タイプ)
- 塗り
- 文字(2タイプ)
- Image(2タイプ)
線
Canvas { context, size in
let path1 = Path {path in
path.move(to: CGPoint(x: 50, y: 10))
path.addLine(to: CGPoint(x: 100, y: 30))
}
context.stroke(path1, with: .color(.red))//太さはデフォルトの1
let path2 = Path {path in
path.move(to: CGPoint(x: 50, y: 30))
path.addLine(to: CGPoint(x: 100, y: 50))
}
context.stroke(path2, with: .color(.blue), lineWidth: 5)
let path3 = Path {path in
path.move(to: CGPoint(x: 50, y: 50))
path.addLine(to: CGPoint(x: 100, y: 70))
}
context.stroke(path3,
with: .color(.green),
style: StrokeStyle(lineWidth: 10, lineCap: .round))
}
塗り
Canvas { context, size in
let path4 = Path {path in
path.move(to: CGPoint(x: 50, y: 100))
path.addLine(to: CGPoint(x: 50, y: 150))
path.addLine(to: CGPoint(x: 100, y: 150))
path.closeSubpath()
}
context.fill(path4, with: .color(.yellow))
}
円のPathを書けば円もいけます。
文字
Canvas { context, size in
context.draw(
Text("Text1"),
in: CGRect(x: 200, y: 50, width: 100, height: 100))
context.draw(Text("text2")
.font(.largeTitle)
.foregroundColor(.blue),
at: CGPoint(x: 200, y: 50),
anchor: .bottom)
}
Image
Canvas { context, size in
context.draw(Image(systemName: "heart"),
in: CGRect(x: 250, y: 100, width: 50, height: 80))
context.draw(Image(systemName: "leaf"),
at: CGPoint(x: 250, y: 200),
anchor: .trailing)
}
Discussion