每个UIGraphicsGetCurrentContext有不同的setStroke颜色

时间:2016-11-19 23:23:21

标签: swift uibezierpath

我想为每个UIBezierPath部分设置不同的笔触颜色。但订单完全错误,我不知道如何解决它。

这就是我想要的:

enter image description here

这就是我得到的:

enter image description here

似乎订单错了。有没有办法去"绑定" bezierPath的颜色并将其附加到上下文?我的代码如下。谢谢!

      let size = CGSize(width: 134, height:51)
    UIGraphicsBeginImageContext(size)
    let context = UIGraphicsGetCurrentContext()

    //// Rectangle Drawing
    let rectanglePath = UIBezierPath(roundedRect: CGRect(x: 0.5, y: 0.5, width: 126, height: 50), cornerRadius: 3)
    UIColor.lightGray.setStroke()
    rectanglePath.lineWidth = 1
    rectanglePath.stroke()
    let clipPath: CGPath = rectanglePath.cgPath
    context?.addPath(clipPath)

    //// Rectangle 2 Drawing
    let rectangle2Path = UIBezierPath(roundedRect: CGRect(x: 3, y: 3, width: 121, height: 45), cornerRadius: 3)
    UIColor.green.setFill()
    rectangle2Path.fill()
    let clipPathh: CGPath = rectangle2Path.cgPath
    context?.addPath(clipPathh)

    let rectangle3Path = UIBezierPath(roundedRect: CGRect(x: 128, y: 18, width: 6, height: 14), byRoundingCorners: [.topRight, .bottomRight], cornerRadii: CGSize(width: 3, height: 3))
    UIColor.gray.setFill()
    rectangle3Path.fill()
    let clipPathhh: CGPath = rectangle3Path.cgPath
    context?.addPath(clipPathhh)

    context?.closePath()

    // Convert to UIImage
    let cgimage = context!.makeImage();
    let uiimage = UIImage(cgImage: cgimage!)

    // End the graphics context
    UIGraphicsEndImageContext()

    image.image = uiimage;

1 个答案:

答案 0 :(得分:2)

知道了。自从我使用bezier路径以来已经有一段时间了,但是一些玩游戏发现了问题 - 这一切都在序列中。代码应该是:

let size = CGSize(width: 134, height:51)
UIGraphicsBeginImageContext(size)
let context = UIGraphicsGetCurrentContext()

//// Rectangle Drawing
let rectanglePath = UIBezierPath(roundedRect: CGRect(x: 0.5, y: 0.5, width: 126, height: 50), cornerRadius: 3)
UIColor.lightGray.setStroke()
rectanglePath.lineWidth = 1
let clipPath: CGPath = rectanglePath.cgPath
context?.addPath(clipPath)
rectanglePath.stroke()

//// Rectangle 2 Drawing
let rectangle2Path = UIBezierPath(roundedRect: CGRect(x: 3, y: 3, width: 121, height: 45), cornerRadius: 3)

UIColor.green.setFill()
let clipPathh: CGPath = rectangle2Path.cgPath
context?.addPath(clipPathh)
rectangle2Path.fill()

let rectangle3Path = UIBezierPath(roundedRect: CGRect(x: 128, y: 18, width: 6, height: 14), byRoundingCorners: [.topRight, .bottomRight], cornerRadii: CGSize(width: 3, height: 3))
UIColor.gray.setFill()
let clipPathhh: CGPath = rectangle3Path.cgPath
context?.addPath(clipPathhh)
rectangle3Path.fill()

// Convert to UIImage
let cgimage = context!.makeImage();
let uiimage = UIImage(cgImage: cgimage!)

// End the graphics context
UIGraphicsEndImageContext()


imageView.image = uiimage;

请注意,在添加上下文路径后,您可以执行填充/描边。另请注意,closePath调用没有任何影响,因为您已经通过定义rects来提供整个路径。