views:

105

answers:

3

Hi,

I'm new to objective-C programming for iOS. I'm struggling with a really simple task, drawing an image with code (not just including it in 'interface builder'). Here's the part of my code where I'm trying to put my image into the view:

UIImage *image = [UIImage imageNamed:@"Note.png"];

[image drawAtPoint:CGPointZero];

Simple. I have also tried with some retain and release commands, and even tried to include a second view on top of the old, to draw the image in. Without luck.

Thanks, John.

+1  A: 

Where are you doing this? drawAtPoint will require there to be a valid current drawing context. Most commonly you should call it from inside some view's drawRect method.

If that's correct, check that:

  • the image itself is actually valid
  • its size makes sense
  • it draws sensibly with something like [image drawInRect:[yourView bounds]]

If all those are so, then you've got an interesting problem. Otherwise, either your image is duff or you're drawing at the wrong time.

walkytalky
A: 

The code you posted needs to go in drawRect. Just before drawRect is called, that part of your view is effectively erased, meaning you need to redraw whatever is in the rect that is passed as an argument.

(Note: if you value code simplicity over performance, you can draw the entire view in drawRect rather than only drawing the part that was requested to be drawn.)

Jon Rodriguez
A: 

Not quite working out for me. Tried moving the whole thing to the viewDidLoad method, to make sure the location is not the problem. The image size and type is valid. Works in interface builder.

Now I create the Rect as suggested:

CGRect rectTemp = CGRectMake(0, 0, 300, 300);

Put it in the view:

[view drawRect:rectTemp];

And draw the image in the Rect:

[image drawInRect:rectTemp];

Is there a way to just make the Rect visible in the view by filling it with a color or something? Then I could check if that part is working. Also I doubt that the linking to my view is correct. Sorry for the 'in-knowledge', and thanks for the answers.

John Kofod