2012-04-13 34 views
4

我有這樣的代碼在視圖中的顏色:IOS:在一個視圖中繪製的圖像

UITouch *touch = [touches anyObject]; 
    CGPoint currentPoint = [touch locationInView:drawImage]; 

    UIGraphicsBeginImageContext(drawImage.frame.size); 
    [drawImage.image drawInRect:CGRectMake(0, 0, drawImage.frame.size.width, drawImage.frame.size.height)]; 
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound); 
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), size); 

     CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), r, g, b, a); 

    CGContextBeginPath(UIGraphicsGetCurrentContext()); 
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y); 
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y); 
    CGContextStrokePath(UIGraphicsGetCurrentContext()); 
    drawImage.image = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

我的問題是,我想有一點不變色,但我想用一個特定的形象,被重複(作爲PNG圖像) 可能嗎?

+0

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@「image.png」]]; – Hanuman 2012-04-13 10:31:32

+0

你能解釋一下嗎? – CrazyDev 2012-04-13 10:33:48

回答

8

可以很容易地加載一個單一的UIImage並繪製它:

UIImage *brushImage = [UIImage imageNamed:@"brush.png"]; 
[brushImage drawAtPoint:CGPointMake(currentPoint.x-brushImage.size.width/2, currentPoint.y-brushImage.size.height/2)]; 

這將繪製圖像只是每週期中,不連續的線。如果您想要畫筆圖片的實線,請參閱Objective C: Using UIImage for Stroking

這可能會在每次調用此方法時結束加載圖像文件,從而使其變慢。儘管[UIImage imageNamed:]的結果經常被緩存,但我上面的代碼可以通過存儲筆刷以便以後重用來改進。

說到性能,請在較舊的設備上進行測試。正如所寫,它在我的第二代iPod touch上工作,但任何附加功能都可能導致它在第二代和第三代設備上結結巴巴。 Apple的GLPaint示例,由@Armaan推薦,使用OpenGL進行快速繪製,但涉及更多代碼。

而且,你似乎是在做一個視圖,然後繪製其內容drawImage,想必UIImageView的交互(touchesBegan:touchesMoved:touchesEnded:)。可以存儲繪畫圖像,然後將該視圖的圖層內容設置爲該圖像。這不會改變性能,但代碼會更乾淨。如果您繼續使用drawImage,請通過property訪問它,而不是使用伊娃。

+2

+ 1.說明。 – Iducool 2012-04-14 09:27:04