2016-06-07 147 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()