Hello!
I'm pretty new to the iPhone developing subject.
My idea is to draw pixels on the screen. Actually I got it working but it is very slow. In the simulator it is ok, but on the iPhone I got around three frames per second or so.
Right now I'm just changing three bytes in the buffer from my BitmapContext every time the drawRect method runs. But I guess it is drawing a complete new image.
Do you guys have some ideas on how to optimize this code?
Is there a way of avoiding creating a complete new image and drawing it into the graphics context?
PHP Code:
//
// DrawingView.m
//
#import "DrawingView.h"
@implementation DrawingView
@synthesize firstTouch;
@synthesize lastTouch;
- (id)initWithCoder:(NSCoder*)coder
{
if ( ( self = [super initWithCoder:coder] ) )
{
firstRun = TRUE;
[self setupBitmapContext];
}
return self;
}
- (void)drawRect:(CGRect)rect
{
CGContextRef myContext = UIGraphicsGetCurrentContext();
if (bitmapData != NULL)
{
int posY = MAX(0, round( pixelsHigh - lastTouch.y - 1.0));
int posX = round( lastTouch.x );
int offset = 4 * ( ( pixelsWide * posY ) + posX );
bitmapData[offset+1] = 255;
bitmapData[offset+2] = 255;
bitmapData[offset+3] = 255;
}
bitmapImage = CGBitmapContextCreateImage (bitmapContext);
CGContextDrawImage(myContext, bitmapRect, bitmapImage);
}
-(void)setupBitmapContext
{
pixelsWide = 320;
pixelsHigh = 400;
bitmapBytesPerRow = (pixelsWide * 4);
bitmapByteCount = (pixelsWide * pixelsHigh * 4);
colorSpace = CGColorSpaceCreateDeviceRGB();
if (colorSpace == NULL) NSLog(@"Error allocating color space");
bitmapData = malloc( bitmapByteCount );
if (bitmapData == NULL)
{
NSLog(@"Memory not allocated!");
CGColorSpaceRelease( colorSpace );
}
bitmapContext = CGBitmapContextCreate (bitmapData,
pixelsWide,
pixelsHigh,
8,
bitmapBytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedFirst);
if (bitmapContext == NULL)
{
free (bitmapData);
NSLog(@"Context not created!");
}
bitmapRect = CGRectMake(0.0, 0.0, pixelsWide, pixelsHigh-3);
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
firstTouch = [touch locationInView:self];
lastTouch = [touch locationInView:self];
[self setNeedsDisplay];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
lastTouch = [touch locationInView:self];
[self setNeedsDisplay];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
lastTouch = [touch locationInView:self];
[self setNeedsDisplay];
}
- (void)dealloc
{
[super dealloc];
}
@end
You can also download this class here:
http://www.rwichmann.com/downloads/DrawingView.m
Thank you for every tipp!
Cheers,
Raphael