Kito
Kito

Reputation: 1385

setNeedsDisplay for UIImage doesn't work

I am trying to draw a line on an UIImage with the help of a dataBuffer when a button gets touched, but the drawRect: .. methode doesn´t get called. (so, the line i want to draw does't appear)

I really don't know where the problem could be, so I posted quite a bit more code. Sorry about that.

By the way, I am working on an viewbasedapplication.

here is my code :

-(void) viewDidLoad{
  UIImage *image = [UIImage imageNamed:@"playView2.jpg"];
  [playView setImage:image];
  [image retain];
  offScreenBuffer = [self setupBuffer];
}

- (IBAction)buttonTouched:(id)sender {
  [self drawToBuffer];
  [playView setNeedsDisplay];    
}

- (void)drawRect:(CGRect)rect{
  CGImageRef cgImage = CGBitmapContextCreateImage(offScreenBuffer);
  UIImage *uiImage = [[UIImage alloc] initWithCGImage:cgImage];
  CGImageRelease(cgImage);
  [uiImage drawInRect: playView.bounds];
  [uiImage release];
}



-(void)drawToBuffer {

//                  Red  Gr   Blu  Alpha
CGFloat color[4] = {1.0, 1.0, 0.0, 1.0};

CGContextSetRGBStrokeColor(offScreenBuffer, color[0], color[1], color[2], color[3]);

CGContextBeginPath(offScreenBuffer);
CGContextSetLineWidth(offScreenBuffer, 10.0);
CGContextSetLineCap(offScreenBuffer, kCGLineCapRound);

CGContextMoveToPoint(offScreenBuffer, 30,40);
CGContextAddLineToPoint(offScreenBuffer, 150,150);

CGContextDrawPath(offScreenBuffer, kCGPathStroke);
}

-(CGContextRef)setupBuffer{      
    CGSize size = playView.bounds.size;

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    CGContextRef context = CGBitmapContextCreate(NULL, size.width, size.height, 8, size.width*4, colorSpace, kCGImageAlphaPremultipliedLast);

    CGColorSpaceRelease(colorSpace);
    return context;
}

Upvotes: 1

Views: 1885

Answers (2)

Rok Jarc
Rok Jarc

Reputation: 18865

I know this is an old question but still, someone might come across here:

the same (or very similiar) question is correctly answered here:

drawRect not being called in my subclass of UIImageView

UIImageView class (and it's sublasses) don't call drawRect if you call their setNeedsDisplay.

Upvotes: 1

jrturton
jrturton

Reputation: 119242

Where is this code? viewDidLoad is a view controller method, drawRect is a view method. Whatever playView is (presumably a UIImageView?) needs to be a custom UIView subclass with your drawRect inside it, and you'll have to pass the various items to that from your view controller.

Upvotes: 1

Related Questions