2016-01-09 79 views
1

我試圖用下面的swift代碼畫一個圖標,但我得到了「虛線」。我剛剛使用moveToPointaddLineToPoint函數。在下面的圖像中,我也看到了與其他繪圖相同的圖形故障。我使用Xcode 7.2並在iOS 9.2.1上運行代碼。爲什麼使用Core Graphics繪製直線我得到「虛線」?

@IBDesignable class DeleteButton: UIButton { 

    override func drawRect(rect: CGRect) { 

     UIColor.blackColor().setStroke() 
     let lineWidth = CGFloat(1) 

     // Draw empty circle 
     let frame = CGRect(x: rect.origin.x + lineWidth, y: rect.origin.y + lineWidth, width: rect.width - (lineWidth * 2), height: rect.height - (lineWidth * 2)) 
     let path = UIBezierPath(ovalInRect: frame) 
     path.lineWidth = lineWidth 

     path.stroke() 

     // Draw X 
     let radius = (rect.width/2) * 0.5 
     let center = CGPoint(x: rect.width/2, y: rect.height/2) 

     let π = CGFloat(M_PI) 
     let centerWidth = radius * cos(π/4) 
     let centerHeight = radius * sin(π/4) 

     path.lineWidth = lineWidth 

     path.moveToPoint(CGPoint(x: CGFloat(center.x + centerWidth), y: CGFloat(center.y + centerHeight))) 
     path.addLineToPoint(CGPoint(x: CGFloat(center.x - centerWidth), y: CGFloat(center.y - centerHeight))) 
     path.stroke() 

     path.lineWidth = lineWidth 

     path.moveToPoint(CGPoint(x: center.x - centerWidth, y: center.y + centerHeight)) 
     path.addLineToPoint(CGPoint(x: center.x + centerWidth, y: center.y - centerHeight)) 
     path.stroke() 
    } 
} 

這是結果:

我爲我的英語不好道歉。

回答

4

我相信你看到按鈕的標題文字在圖像上繪製的結果。看看下面的演示使用你的代碼在遊樂場:

enter image description here

0

我們需要知道代碼運行的上下文。你不能開始繪畫。

繪製視圖的常用方法是重寫drawRect方法。當你這樣做時,系統的圖形上下文正確設置了一個遮罩,該遮罩將圖形剪切到視圖的邊界,座標系設置爲視圖的座標等。

如果您的圖形代碼不在視圖中drawRect方法那麼這就是你的問題。

+0

這很奇怪。繪圖上下文可能有一個線條集,或者可能存在覆蓋部分繪圖的活動遮罩。嘗試在繪圖上下文中使用CGContextSetLineDash,並使用nil數組和0計數。如果您只是創建一個矩形貝塞爾路徑作爲整個視圖的大小並用純色填充,會發生什麼情況?你還看到白色嗎? –

相關問題