2013-05-29 67 views
1

我可以繪製形狀像圓,矩形,線等外部使用我可以繪製形狀像圓,矩形,線等的drawRect方法以外

CGContextRef contextRef = UIGraphicsGetCurrentContext(); 

或者是強制性的,以使用它的內部只有drawRectdrawRect方法。 請幫助我,讓我知道如何在drawRect方法外繪製形狀。 其實我想繼續在touchesMoved事件上繪製點。

這是我繪製點的代碼。

CGContextRef contextRef = UIGraphicsGetCurrentContext(); 
CGContextSetRGBFillColor(contextRef, 0, 255, 0, 1); 
CGContextFillEllipseInRect(contextRef, CGRectMake(theMovedPoint.x, theMovedPoint.y, 8, 8)); 
+0

當然,創建位圖上下文中,拉入它們,然後創建從這些圖像。 –

回答

12

基本上你需要一個上下文來繪製一些東西。您可以將上下文假定爲白皮書。 UIGraphicsGetCurrentContext將返回null如果您不在有效的上下文中。drawRect您將獲得該視圖的上下文。

話雖如此,你可以在drawRect之外畫方法。你可以開始一個imageContext來繪製東西並將其添加到你的視圖中。

看從here採取下面的例子中,

- (UIImage *)imageByDrawingCircleOnImage:(UIImage *)image 
{ 
    // begin a graphics context of sufficient size 
    UIGraphicsBeginImageContext(image.size); 

    // draw original image into the context 
    [image drawAtPoint:CGPointZero]; 

    // get the context for CoreGraphics 
    CGContextRef ctx = UIGraphicsGetCurrentContext(); 

    // set stroking color and draw circle 
    [[UIColor redColor] setStroke]; 

    // make circle rect 5 px from border 
    CGRect circleRect = CGRectMake(0, 0, 
       image.size.width, 
       image.size.height); 
    circleRect = CGRectInset(circleRect, 5, 5); 

    // draw circle 
    CGContextStrokeEllipseInRect(ctx, circleRect); 

    // make image out of bitmap context 
    UIImage *retImage = UIGraphicsGetImageFromCurrentImageContext(); 

    // free the context 
    UIGraphicsEndImageContext(); 

    return retImage; 
} 
1

對於夫特4

func imageByDrawingCircle(on image: UIImage) -> UIImage { 
    UIGraphicsBeginImageContextWithOptions(CGSize(width: image.size.width, height: image.size.height), false, 0.0) 

    // draw original image into the context 
    image.draw(at: CGPoint.zero) 

    // get the context for CoreGraphics 
    let ctx = UIGraphicsGetCurrentContext()! 

    // set stroking color and draw circle 
    ctx.setStrokeColor(UIColor.red.cgColor) 

    // make circle rect 5 px from border 
    var circleRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height) 
    circleRect = circleRect.insetBy(dx: 5, dy: 5) 

    // draw circle 
    ctx.strokeEllipse(in: circleRect) 

    // make image out of bitmap context 
    let retImage = UIGraphicsGetImageFromCurrentImageContext()! 

    // free the context 
    UIGraphicsEndImageContext() 

    return retImage; 
} 
相關問題