2016-06-07 146 views
3

如何检查UIBezierPath是否为封闭路径(封闭路径就像是封闭的轮廓意味着它会创建像三角形,正方形,多边形等任何形状),如果封闭,那么只填写路径?检查UIBezierPath是否关闭

以下代表应该填充形状的区域;最后2形状限定闭合轮廓和简单闭合轮廓,其在唯一的颜色可被填充:

enter image description here

Image Source

以下是我的相同的代码,有4个方块在它,但在填充只有3个方格;还想知道是否有可能找到填充面积以平方英尺为单位,因为我在这里得到4个方格,如何检查它在4个方格中覆盖的总面积?

UIBezierPath *mainPath =[UIBezierPath bezierPath]; 
[mainPath moveToPoint:CGPointMake(50, 100)]; 
[mainPath addLineToPoint:CGPointMake(0, 100)]; 
[mainPath addLineToPoint:CGPointMake(0, 150)]; 
[mainPath addLineToPoint:CGPointMake(50, 150)]; 
[mainPath addLineToPoint:CGPointMake(50, 200)]; 
[mainPath addLineToPoint:CGPointMake(100, 200)]; 
[mainPath addLineToPoint:CGPointMake(100, 150)]; 
[mainPath addLineToPoint:CGPointMake(50, 150)]; 
[mainPath addLineToPoint:CGPointMake(50, 100)]; 
[mainPath addLineToPoint:CGPointMake(100, 100)]; 
[mainPath addLineToPoint:CGPointMake(150, 100)]; 
[mainPath addLineToPoint:CGPointMake(150, 150)]; 
[mainPath addLineToPoint:CGPointMake(100, 150)]; 
[mainPath addLineToPoint:CGPointMake(100, 100)]; 
CAShapeLayer *shapeLayer = [[CAShapeLayer alloc] init]; 
shapeLayer.lineWidth = 5.0; 
shapeLayer.strokeColor = [UIColor blueColor].CGColor; 
shapeLayer.path =mainPath.CGPath; 
shapeLayer.fillColor = [[UIColor redColor] colorWithAlphaComponent:0.5].CGColor; 
[[self.view layer] addSublayer:shapeLayer]; 

回答

0

你为什么不使用mainPath.closePath它会自动关闭路径为你和填充。如果你想有关于自动关闭路径,或者手动,你可以看看here更多的信息,它说:

不同的是,在[closePath]方法实际上增加了一个 附加路径元素添加到底层CGPath那支持UIBezierPath的 。

如果使用[closePath],再追加CGPathElement与一种类型的kCGPathElementCloseSubpath将 最后一行段之后立即被追加到路径 的末尾。

对于所覆盖的区域,你可以得到你UIBezierPath的边框,但我认为这可能是更简单的让你有不同的UIBezierPath(一个为每个平方的),然后计算边界框每个广场。如果你想拥有你的路径的边界框:

let bounds = CGPathGetBoundingBox(yourPath.CGPath) 
+2

好,被动态地添加所有行,我不想closePath;我只是想检查它是封闭的或不是这样。并且考虑到该区域,那么形状可以是任何类似三角形的形状,因此该面积可以被计算为所有不同的形状(以平方英尺为单位)。 –

1

我已经回答了类似的问题有关CGPathhere。既然你可以得到CGPathUIBezierPath,我认为它也适用于这里。这是Swift 3.x.我借用沉重this answer,增加isClosed()功能。

extension CGPath { 

func isClosed() -> Bool { 
    var isClosed = false 
    forEach { element in 
     if element.type == .closeSubpath { isClosed = true } 
    } 
    return isClosed 
} 

func forEach(body: @convention(block) (CGPathElement) -> Void) { 
    typealias Body = @convention(block) (CGPathElement) -> Void 
    let callback: @convention(c) (UnsafeMutableRawPointer, UnsafePointer<CGPathElement>) -> Void = { (info, element) in 
     let body = unsafeBitCast(info, to: Body.self) 
     body(element.pointee) 
    } 
    print(MemoryLayout.size(ofValue: body)) 
    let unsafeBody = unsafeBitCast(body, to: UnsafeMutableRawPointer.self) 
    self.apply(info: unsafeBody, function: unsafeBitCast(callback, to: CGPathApplierFunction.self)) 
} 
} 

这里是你如何使用它:

myBezierPath.cgPath.isClosed()