Following on from dynamic clocks.

It would also be nice to draw multiple clocks if one is ‘full’ it starts another. This example draws and returns a maximum of three clocks but always returns a 90×30 image:


- (UIImage *)drawClocks:(NSNumber *)time {
	UIImage *image;
	int clock1=0, clock2=0, clock3=0;
	CGRect rect = CGRectMake(0,0,90,30);
	UIGraphicsBeginImageContext(rect.size);
	CGContextRef context = UIGraphicsGetCurrentContext();
	
	// We wish to draw clocks right to left according to how many minutes we have, max of 180m.
	int era = [time intValue];
	if(era>59) {
		clock1 = 60;
	}
	else {
		clock1 = era;
	}
	if (era>119) {
		clock2 = 60;
	} else {
		clock2 = era>60?era%60:0;
	}
	if (era>179) {
		clock3 = 60;
	} else {
		clock3 = era>120?era%60:0;
	}

	if (clock1) {
		UIImage *image1 = [self drawTime:[NSNumber numberWithInt:clock1]];
		CGContextDrawImage(context, CGRectMake(0, 0, 30, 30), [image1 CGImage]);
	}
	if (clock2) {
		UIImage *image2 = [self drawTime:[NSNumber numberWithInt:clock2]];
		CGContextDrawImage(context, CGRectMake(30, 0, 30, 30), [image2 CGImage]);
	}
	if (clock3) {
		UIImage *image3 = [self drawTime:[NSNumber numberWithInt:clock3]];
		CGContextDrawImage(context, CGRectMake(60, 0, 30, 30), [image3 CGImage]);
	}
	
	image = UIGraphicsGetImageFromCurrentImageContext();

	UIGraphicsEndImageContext();
	
	return image;
}

Also the <A HREF="http://www.thelostsouls.org More Help.uk/2010/08/drawing-little-clock-icons-dynamically”>last post mentioned that the eventual UI view would need to do the rotate. If this is added straight after the context is obtained:


	// Save our current state (effectively inverted y for iOS)
	CGContextSaveGState(context);
	// Move image UP
	CGContextTranslateCTM(context, 0, 30);
	// Flip Y Axis
	CGContextScaleCTM(context, 1.0, -1.0);
	// Rotate 90 degrees
	CGContextRotateCTM(context, -M_PI/2);
	// Move it Back down so it's in our frame again.
	CGContextTranslateCTM(context, -30, 0);

	// It really helps if you're stuck to draw your image on a bit of paper and flip/rotate it visually.
	// E.g. I draw my 45 minute clock on a bit of paper with 0 marked on the east then tried rotations/flips
	// to get the view I wanted.  then wrote them out above!

You don’t need to include my last comment… then add this before you get the image:

	// Restore original context.
	CGContextRestoreGState(context);

No more rotation is needed. It’s left as an exercise to whomever as to why the translations above produce the correct orientation. I really did draw it on a little square of paper. 😛

This entry was posted in Programming and tagged , , , , , , . Bookmark the permalink.