khalid soofi
khalid soofi

Reputation: 181

Looking for a simple pixel drawing method in ios (iphone, ipad)

I have a simple drawing issue. I have prepared a 2 dimensional array which has an animated wave motion. The array is updated every 1/10th of a second (this can be changed by the user). After the array is updated I want to display it as a 2 dimensional image with each array value as a pixel with color range from 0 to 255.

Any pointers on how to do this most efficiently...

Appreciate any help on this...

KAS

Upvotes: 1

Views: 2223

Answers (1)

Tommy
Tommy

Reputation: 100602

If it's just a greyscale then the following (coded as I type, probably worth checking for errors) should work:

CGDataProviderRef dataProvider =
       CGDataProviderCreateWithData(NULL, pointerToYourData, width*height, NULL);

CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceGray();
CGImageRef inputImage = CGImageCreate(  width, height,
                                        8, 8, width, 
                                        colourSpace, 
                                        kCGBitmapByteOrderDefault,
                                        dataProvider,
                                        NULL, NO,
                                        kCGRenderingIntentDefault);
CGDataProviderRelease(dataProvider);
CGColorSpaceRelease(colourSpace);

UIImage *image = [UIImage imageWithCGImage:inputImage];
CGImageRelease(inputImage);

someImageView.image = image;

That'd be for a one-shot display, assuming you didn't want to write a custom UIView subclass (which is worth the effort only if performance is a problem, probably).

My understanding from the docs is that the data provider can be created just once for the lifetime of your C buffer. I don't think that's true of the image, but if you created a CGBitmapContext to wrap your buffer rather than a provider and an image, that would safely persist and you could use CGBitmapContextCreateImage to get a CGImageRef to be moving on with. It's probably worth benchmarking both ways around if it's an issue.

EDIT: so the alternative way around would be:

// get a context from your C buffer; this is now something
// CoreGraphics could draw to...
CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceGray();
CGContextRef context = 
        CGBitmapContextCreate(pointerToYourData,
                              width, height,
                              8, width,
                              colourSpace,
                              kCGBitmapByteOrderDefault);
CGColorSpaceRelease(colourSpace);

// get an image of the context, which is something
// CoreGraphics can draw from...
CGImageRef image = CGBitmapContextCreateImage(context);

/* wrap in a UIImage, push to a UIImageView, as before, remember
   to clean up 'image' */

CoreGraphics copies things about very lazily, so neither of these solutions should be as costly as the multiple steps imply.

Upvotes: 2

Related Questions