1

in my application, I have a view named mainvie - when the application runs, mainview is loaded which loads a background image onto the screen ( code below) ring_large.jpg has been added as a file.

- (void)drawRect:(CGRect)rect {
UIImage *image = [UIImage imageNamed:@"rink_large.jpg"];
CGPoint imagepoint = CGPointMake(10,0); 
[image drawAtPoint:imagepoint];
}

This works fine, it is when I am trying to draw another image on top of this that I am having issues. Elsewhere (file named mainviewcontroller.m) - On a touch even I am trying to get the location of the touch, and draw an image at the location. Listed below is my code. I am not sure why the image I am trying to place is not drawing at all. I am sure it is not drawing behind the rink image, as i commented this out and the image still doesnt draw when clicked. Here is the touches begin function which should draw the image.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
     CGPoint location = [[touches anyObject] locationInView:mainView];
    UIImage *image = [UIImage imageNamed:@"small_cone.png"];
    [image drawAtPoint:location];
}

Can anyone see why the image will not draw when somewhere is touched? The touchesBegan function start when the screen is touched anywhere, but the picture is not displaying. Thanks for your help, I am newer to objective - c.

njj56
  • 611
  • 4
  • 19
  • 51

1 Answers1

2

UIImage drawAtPoint draws the image within the current graphics context. You are not defining a graphics context. In drawRect (where your original code is) there is already a graphics context. Basically, you are telling the UIImage what location to draw at, but not what to draw on.

You need something more like this:

CGPoint location = [[touches anyObject] locationInView:mainView];

UIGraphicsBeginImageContext(mainView.bounds.size);
UIImage *image = [UIImage imageNamed:@"small_cone.png"];
[image drawAtPoint:location];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

However, this won't preserve or take into account your original image. If you want them both drawn, one over the other, use drawAtPoint for both images:

CGPoint location = [[touches anyObject] locationInView:mainView];

UIGraphicsBeginImageContext(mainView.bounds.size);

UIImage *image = [UIImage imageNamed:@"rink_large.jpg"];
CGPoint imagepoint = CGPointMake(10,0);
[image drawAtPoint:imagepoint];

image = [UIImage imageNamed:@"small_cone.png"];
[image drawAtPoint:location];

UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Now you can do something with newImage, which contains a composite of both images.

Nathanial Woolls
  • 5,231
  • 24
  • 32
  • Thank you! I was able to take newImage and store this in a UIImage declared in mainview.h with the other view, set the image on load to just the rink, then update this every time a cone is put in. Thanks again. – njj56 Oct 25 '12 at 13:16