IOS: draw an image in a view

ios, png, uiimage, xcode

Solution

It's easy to load a single UIImage and draw it:

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

This will draw the image just once per cycle, not a continuous line. If you want solid lines of your brush picture, see Objective C: Using UIImage for Stroking.

This could end up loading the image file every time this method is called, making it slow. While the results of `[UIImage imageNamed:]` are often cached, my code above could be improved by storing the brush for later reuse.

Speaking of performance, test this on older devices. As written, it worked on my second generation iPod touch, but any additions could make it stutter on second and third generation devices. Apple's GLPaint example, recommended by @Armaan, uses OpenGL for fast drawing, but much more code is involved.

Also, you seem to be doing your interaction (`touchesBegan:`, `touchesMoved:`, `touchesEnded:`) in a view that then draws its contents to `drawImage`, presumably a `UIImageView`. It is possible to store the painting image, then set this view's layer contents to be that image. This will not alter performance, but the code will be cleaner. If you continue using `drawImage`, access it through a `property` instead using its ivar.

Problem

I have this code to color in a view: ``` 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(); ``` my problem is that I want to color not with a point, but I want to use a particular image that is repeated (as a png image) Is it possible?

Original source