2016-07-16 216 views
-1

我試圖畫一個矩形觸摸。到目前爲止,我有兩段代碼,第一個是目前繪製一個圓的方法,第二個代碼添加了形狀以查看,我如何繪製矩形?Swift繪製矩形

func drawRectangle() { 
    // Get the Graphics Context 
    let context = UIGraphicsGetCurrentContext(); 

    // Set the rectangle outerline-width 
    CGContextSetLineWidth(context, 5.0); 

    // Set the rectangle outerline-colour 
    UIColor.redColor().set() 

    // Create Rectangle 

    CGContextAddArc(context, (frame.size.width)/2, frame.size.height/2, (frame.size.width - 10)/2, 0.0, CGFloat(M_PI * 2.0), 1) 

    // Draw 
    CGContextStrokePath(context); 
} 

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 

    let rectangleCenter = touches.first!.locationInView(view) 

    let rectangleWidth = CGFloat(50) 
    let rectangleHeight = rectangleWidth 

    // Create a new rectangleView 
    let rectangleView = Annotations(frame: CGRectMake(rectangleCenter.x, rectangleCenter.y, rectangleWidth, rectangleHeight), shape: 1) 

    view.addSubview(rectangleView) 
} 

我曾嘗試以下:

// Create Rectangle 
     CGContextAddRect(context, CGRectMake((frame.size.width)/2, frame.size.height/2, 40, 40)); 

它創建與頂部的線與線下左邊的矩形的左上角的一部分。我如何調整這是一個完整的矩形?

+2

如果您在查找CGContextAddArc CGContext引用然後CGContextAddRect是不是很遠...... :) –

+0

嗨馬丁R,我試過CGContextAddRect,它給了我一個矩形的一半 – user979331

+2

然後你cre吃錯了矩形。 CGRectMake的前兩個參數是原點(左上角),而不是中點。 –

回答

-1

我能夠通過執行以下操作來解決我的問題:

增加寬度和高度的位置:

let rectangleWidth = CGFloat(100) 
let rectangleHeight = rectangleWidth 

和我的矩形法

func drawRectangle() 
    { 
     // Get the Graphics Context 
     let context = UIGraphicsGetCurrentContext(); 

     // Set the rectangle outerline-width 
     CGContextSetLineWidth(context, 5.0); 

     // Set the rectangle outerline-colour 
     UIColor.redColor().set() 

     // Create Rectangle 
     CGContextAddRect(context, CGRectMake(0, 0, 100, 100)); 

     // Draw 
     CGContextStrokePath(context); 

    }