2013-07-06 3 views
3

У меня есть метод, который создает пустой миниатюры для представления таблицы, в котором я пытаюсь центрировать некоторый текст.Вертикально текст центра в контексте с использованием Quartz 2D

Центрирование по горизонтали достаточно просто, рисуя невидимый текст, но никто, кажется, не иллюстрирует, как центрировать текст по вертикали. Я пробовал несколько разных вещей, и ничто не дает по-настоящему сосредоточенного текста.

Как рассчитать начало 'y' для CGContextShowTextAtPoint(), что приведет к тому, что выходной текст будет центрирован по вертикали?

см ниже, например, изображения, и код для метода:

enter image description here

- (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; 
} 

Спасибо. Если вы видите что-то еще не так, пожалуйста, дайте мне знать.

ответ

2

Я изменил ваш метод и сделал размер изображения размером 66 x 100, я также удалил невидимый вариант.

Теперь вы увидите изображение, центрированное по вертикали. Здесь вы найдете:

- (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 = 100 * 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); 

for (int i = 0;i < string.length; i++) 
{ 
    NSInteger inc = string.length - i - 1; 
    NSRange range; 
    range.length = 1; 
    range.location = inc; 
    NSString *si = [string substringWithRange:range]; 
    CGSize letterSize = [si sizeWithFont:[UIFont fontWithName:@"Helvetica" size:size]]; 
    // Calculate height & width, and center text in context 
    CGFloat x = (width/2) - letterSize.width/2; 
    CGFloat y = i * size; 


    // Set Drawing Mode to Fill Stroke 
    CGContextSetTextDrawingMode (context, kCGTextFillStroke); 

    // Draw Text 
    CGContextShowTextAtPoint (context, x, y, si.UTF8String, si.length); 

} 
// Set Drawing Mode to Invisible 


// Get initial and final positions 


// 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; 
} 
+0

Интересная часть кода, но не совсем то, что я ищу. Я хочу, чтобы текст отображался так же, как в моем образце, за исключением того, что он перемещался всего на несколько пикселей до истинного вертикального центра контекста. – Pat

+0

'sizeWithFont:' мне гораздо лучше, чем делать с невидимыми персонажами, как предложено [здесь] (https://developer.apple.com/library/mac/documentation/graphicsimaging/conceptual/drawingwithquartz2d/dq_text/dq_text.html # // apple_ref/doc/uid/TP30001066-CH213-SW2) –

+0

@MartinBerger определенно, зачем писать дважды то же самое?! – soryngod