3
일부 텍스트를 가운데 맞추려고하는 테이블 뷰의 빈 축소판을 만드는 메서드가 있습니다.Quartz 2D를 사용하여 컨텍스트의 텍스트를 가운데에 맞 춥니 다
수평으로 가운데 맞추기는 보이지 않는 텍스트를 그리기 만하면되지만 아무도 텍스트를 세로로 가운데 맞추는 방법을 설명하는 것처럼 보이지 않습니다. 나는 몇 가지 다른 것들을 시도했지만 진정한 가운데에있는 텍스트를 제공하는 것은 없습니다.
CGContextShowTextAtPoint()
의 'y'원점을 계산하면 출력 텍스트의 세로 가운데 정렬이 어떻게됩니까?
예 이미지는 아래를 참조하고, 메서드에 대한 코드 :
- (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;
}
감사합니다. 방법에 문제가있는 것이 보이면 알려주십시오.
재미있는 비트의 코드지만 내가 찾고있는 것이 아니다. 컨텍스트의 진정한 수직 중심으로 단지 몇 픽셀 위로 이동하는 것을 제외하고 텍스트가 샘플 이미지와 같이 표시되도록하고 싶습니다. – Pat
'sizeWithFont :'내게는 보이지 않는 문자를 사용하는 것이 좋습니다. [here] (https://developer.apple.com/library/mac/documentation/graphicsimaging/conceptual/drawingwithquartz2d/dq_text/dq_text.html) #/apple_ref/doc/uid/TP30001066-CH213-SW2) –
@MartinBerger 확실히, 왜 똑같은 것을 두 번 써야합니까?! – soryngod