I have a method which creates a blank thumbnail for a Table View in which I am trying to center some text.
Centering horizontally is easy enough by drawing the invisible text, but nobody seems to illustrate how to center the text vertically. I've tried a few different things and nothing provides truly centered text.
How do I calculate the 'y' origin for CGContextShowTextAtPoint()
which will result in the output text being centered vertically?
See below for example image, and the code for the method:
- (UIImage *)blankThumbnail
{
// Check to see if Blank Thumbnail has already been initialized
if (_blankThumbnail != nil) {
return _blankThumbnail;
}
// Get Device Scale
CGFloat scale = [[UIScreen mainScreen] scale];
// Setup color space
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
// Create a CGBitmapContext to draw an image into
NSUInteger width = 66 * scale;
NSUInteger height = 44 * scale;
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(NULL,
width,
height,
bitsPerComponent,
bytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
// Release colorspace
CGColorSpaceRelease(colorSpace);
// Set the Fill Area to the full size of context
CGRect fillArea = CGRectMake(0, 0, width, height);
// Set Fill Color and Fill Context
CGContextSetRGBFillColor(context, 200.0f/255.0f, 200.0f/255.0f, 200.0f/255.0f, 1.0f);
CGContextFillRect(context, fillArea);
// Set Text String and Size
NSString *string = @"No Image";
CGFloat size = 12 * scale;
// Set up Font
CGContextSelectFont(context,
"Helvetica",
size,
kCGEncodingMacRoman);
// Set Fill and Stroke Colors
CGContextSetRGBFillColor(context, 0, 0, 0, 0.4);
CGContextSetRGBStrokeColor(context, 0, 0, 0, 0.4);
// Set Drawing Mode to Invisible
CGContextSetTextDrawingMode(context, kCGTextInvisible);
// Get initial and final positions
CGPoint initPos = CGContextGetTextPosition(context);
CGContextShowTextAtPoint (context, initPos.x, initPos.y, string.UTF8String, string.length);
CGPoint finalPos = CGContextGetTextPosition(context);
// Calculate height & width, and center text in context
CGFloat x = (width / 2) - ((finalPos.x - initPos.x) / 2);
CGFloat y = (height / 2) - (size / 2);
// Set Drawing Mode to Fill Stroke
CGContextSetTextDrawingMode (context, kCGTextFillStroke);
// Draw Text
CGContextShowTextAtPoint (context, x, y, string.UTF8String, string.length);
// Get CGImage and set to UIImage
CGImageRef imageRef = CGBitmapContextCreateImage(context);
// Release context
CGContextRelease(context);
// Set CGImage to UIImage
_blankThumbnail = [UIImage imageWithCGImage:imageRef];
// Release Image Ref
CGImageRelease(imageRef);
return _blankThumbnail;
}
Thanks. If you see anything else wrong with the method please let me know.