gpt4 book ai didi

ios - 在 Swift 中用特定颜色绘制路径/矩形有什么等价的

转载 作者:行者123 更新时间:2023-11-28 10:46:16 24 4
gpt4 key购买 nike

在 Android(在 Java)中,我可以做这样的事情(这里我尝试绘制三角形图形,它填充了不同的颜色,前半部分为红色,第二部分为绿色,三角形图形周围还有黑色描边:

@Override
public void onDraw(Canvas canvas) {

....

canvas.clipPath(pathBoundary); // triangle figure path
canvas.drawPath(pathBoundary, paintBlack); // draw black stroke around figure
canvas.drawRect(rectRed, paintRed); // fill first half with red color
canvas.drawRect(rectGreen, paintGreen); // fill second half with green color

在 iOS 中我刚刚学会了如何只用一种颜色绘制三角形图形,也想用两种颜色绘制(就像在 Android 中一样)

  override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
context.beginPath()
context.move(to: CGPoint(x: rect.minX, y: rect.maxY))
context.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
context.addLine(to: CGPoint(x: (rect.maxX / 2.0), y: rect.minY))
context.setFillColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 0.60)
context.fillPath()
context.clip()
... how to draw path with specific color?
... how to draw rect with specific color?

enter image description here

最佳答案

您可以像在 Android 上那样做:绘制三角形路径,将其设置为剪切路径,绘制红色矩形,绘制绿色矩形。

UIGraphicsBeginImageContext(CGSize(width: 200, height: 200))
let context = UIGraphicsGetCurrentContext()!
context.beginPath()
context.move(to: CGPoint(x: 100, y: 0))
context.addLine(to: CGPoint(x: 0, y: 200))
context.addLine(to: CGPoint(x: 200, y: 200))
context.closePath()
let path = context.path!
context.setStrokeColor(UIColor.black.cgColor)
context.strokePath()
context.addPath(path)
context.clip()
context.setFillColor(UIColor.red.cgColor)
context.fill(CGRect(x: 0, y: 0, width: 200, height: 150))
context.setFillColor(UIColor.green.cgColor)
context.fill(CGRect(x: 0, y: 150, width: 200, height: 50))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

您可以在 Playground 上运行上面的代码。在右栏中,将鼠标悬停在最后一行(图像行)上,单击眼睛图标,您将看到所绘制图像的预览。

关于ios - 在 Swift 中用特定颜色绘制路径/矩形有什么等价的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48446867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com