代码之家  ›  专栏  ›  技术社区  ›  Steve Folly

如何使用nsstring drawinrect使文本居中?

  •  40
  • Steve Folly  · 技术社区  · 16 年前

    我怎么画 NSString 以A为中心 NSRect ?

    我从:(自定义视图的DrawRect方法的一个摘录)开始。

    NSString* theString = ...
    [theString drawInRect:theRect withAttributes:0];
    [theString release];
    

    现在我假设我需要设置一些属性。我已经浏览了苹果公司的Cocoa文档,但是它有点让人难以接受,并且找不到任何关于如何将段落样式添加到属性中的内容。

    而且,我只能找到 水平的 对齐,怎么样 垂直的 对准?

    10 回复  |  直到 7 年前
        1
  •  90
  •   ricardokrieg    8 年前

    垂直对齐你必须自己做((视图高度+字符串高度)/2)。水平对齐可以使用:

    NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    style.alignment = NSTextAlignmentCenter;
    NSDictionary *attr = [NSDictionary dictionaryWithObject:style forKey:NSParagraphStyleAttributeName];
    [myString drawInRect:someRect withAttributes:attr];
    
        2
  •  27
  •   Alex Cio Olie    10 年前

    这对我的水平对齐很有用

    [textX drawInRect:theRect 
             withFont:font 
        lineBreakMode:UILineBreakModeClip 
            alignment:UITextAlignmentCenter];
    
        3
  •  19
  •   Alex Cio Olie    11 年前

    马丁斯的回答很接近,但有一些小错误。试试这个:

    NSMutableParagraphStyle* style = [[NSMutableParagraphStyle alloc] init];
    [style setAlignment:NSCenterTextAlignment];
    NSDictionary *attr = 
      [NSDictionary dictionaryWithObject:style 
                                  forKey:NSParagraphStyleAttributeName];
    [myString drawInRect:someRect withAttributes:attr];
    [style release];
    

    你必须创建一个新的 NSMutableParagraphStyle (而不是使用马丁建议的默认段落样式)因为 [NSMutableParagraphStyle defaultParagraphStyle] 返回一个 NSParagraphStyle ,它没有setAlignment方法。另外,你不需要绳子 @"NSParagraphStyleAttributeName" 艾尔刚 NSParagraphStyleAttributeName .

        4
  •  12
  •   ZYiOS    12 年前

    这对我很有用:

        CGRect viewRect = CGRectMake(x, y, w, h);
        UIFont* font = [UIFont systemFontOfSize:15];
        CGSize size = [nsText sizeWithFont:font
                         constrainedToSize:viewRect.size
                             lineBreakMode:(UILineBreakModeWordWrap)];  
        float x_pos = (viewRect.size.width - size.width) / 2; 
        float y_pos = (viewRect.size.height - size.height) /2; 
        [someText drawAtPoint:CGPointMake(viewRect.origin.x + x_pos, viewRect.origin.y + y_pos) withFont:font];
    
        5
  •  4
  •   Keith Smiley    11 年前

    [NSMutableParagraphStyle defaultParagraphStyle] 不起作用:

    [NSMutableParagraphStyle new]

    此外,水平对齐似乎只适用于 drawInRect 不是 drawAtPoint (问我怎么知道:—)

        6
  •  4
  •   Kris    9 年前

    对于任何对ios7+改编感兴趣的人,将其放到nsstring类别中:

    - (void)drawVerticallyInRect:(CGRect)rect withFont:(UIFont *)font color:(UIColor *)color andAlignment:(NSTextAlignment)alignment
    {
        rect.origin.y = rect.origin.y + ((rect.size.height - [self sizeWithAttributes:@{NSFontAttributeName:font}].height) / 2);
    
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        [style setAlignment:alignment];
    
        [self drawInRect:rect withAttributes:@{
                                           NSFontAttributeName              : font,
                                           NSForegroundColorAttributeName   : color,
                                           NSParagraphStyleAttributeName    : style
                                           }];
    }
    
        7
  •  2
  •   Joel Levin    16 年前

    好吧,drawinrect只适用于基本文本绘制(换句话说,系统决定将文本放置在何处)-通常在需要的位置绘制文本的唯一方法是简单地计算所需的点并使用nsstring的drawinAtpoint:withattributes:。

    此外,nsstring的sizewithattributes在任何定位数学中都是非常有用的,您最终都需要为drawAtpoint做些什么。

    祝你好运!

        8
  •  1
  •   Julian F. Weinert    10 年前

    正确答案是:

    -drawInRect:withFont:lineBreakMode:alignment:

    我还为垂直对齐创建了一个小类别。如果你喜欢使用它,请继续:)

    // NSString+NSVerticalAlign.h
    typedef enum {
        NSVerticalTextAlignmentTop,
        NSVerticalTextAlignmentMiddle,
        NSVerticalTextAlignmentBottom
    } NSVerticalTextAlignment;
    
    @interface NSString (VerticalAlign)
    - (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font verticalAlignment:(NSVerticalTextAlignment)vAlign;
    - (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font lineBreakMode:(NSLineBreakMode)lineBreakMode verticalAlignment:(NSVerticalTextAlignment)vAlign;
    - (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font lineBreakMode:(NSLineBreakMode)lineBreakMode alignment:(NSTextAlignment)alignment verticalAlignment:(NSVerticalTextAlignment)vAlign;
    @end
    
    
    // NSString+NSVerticalAlign.m
    #import "NSString+NSVerticalAlign.h"
    
    @implementation NSString (VerticalAlign)
    - (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font verticalAlignment:(NSVerticalTextAlignment)vAlign {
    switch (vAlign) {
        case NSVerticalTextAlignmentTop:
            break;
    
        case NSVerticalTextAlignmentMiddle:
            rect.origin.y = rect.origin.y + ((rect.size.height - font.pointSize) / 2);
            break;
    
        case NSVerticalTextAlignmentBottom:
            rect.origin.y = rect.origin.y + rect.size.height - font.pointSize;
            break;
        }
        return [self drawInRect:rect withFont:font];
    }
    - (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font lineBreakMode:(NSLineBreakMode)lineBreakMode verticalAlignment:(NSVerticalTextAlignment)vAlign {
    switch (vAlign) {
        case NSVerticalTextAlignmentTop:
            break;
    
        case NSVerticalTextAlignmentMiddle:
            rect.origin.y = rect.origin.y + ((rect.size.height - font.pointSize) / 2);
            break;
    
        case NSVerticalTextAlignmentBottom:
            rect.origin.y = rect.origin.y + rect.size.height - font.pointSize;
            break;
        }   
        return [self drawInRect:rect withFont:font lineBreakMode:lineBreakMode];
    }
    - (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font lineBreakMode:(NSLineBreakMode)lineBreakMode alignment:(NSTextAlignment)alignment verticalAlignment:(NSVerticalTextAlignment)vAlign {
    switch (vAlign) {
        case NSVerticalTextAlignmentTop:
            break;
    
        case NSVerticalTextAlignmentMiddle:
            rect.origin.y = rect.origin.y + ((rect.size.height - font.pointSize) / 2);
            break;
    
        case NSVerticalTextAlignmentBottom:
            rect.origin.y = rect.origin.y + rect.size.height - font.pointSize;
            break;
        }   
        return [self drawInRect:rect withFont:font lineBreakMode:lineBreakMode alignment:alignment];
    }
    @end
    
        9
  •  1
  •   Kiryl BielaÅ¡eÅ­ski Mkey    7 年前

    只为 网间网操作系统 斯威夫特4 , 使用该方法使字符串在矩形内居中 绘制(in:WithAttributes:)

    let textFont = UIFont.boldSystemFont(ofSize: )
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = .center
    paragraphStyle.minimumLineHeight =  rectangle.height / 2 + textFont.lineHeight / 2
    let textAttributes = [
                NSAttributedStringKey.font: textFont,
                NSAttributedStringKey.paragraphStyle: paragraphStyle
                ] as [NSAttributedStringKey : Any]
    let text = "Text"
    (text as NSString).draw(in: rectangle, withAttributes: textAttributes)
    
        10
  •  0
  •   jalopezsuarez    12 年前

    以下代码段对于使用注释自定义图像作为引用绘制中心文本字符串很有用:

    自定义注释.h

    @interface CustomAnnotation : MKAnnotationView
    [...]
    

    自定义注释.m

    [...]        
           - (void)drawRect:(CGRect)rect
            {
                ClusterAnnotation *associatedAnnotation = (CustomAnnotation *)self.annotation;
                if (associatedAnnotation != nil)
                {
                    CGContextRef context = UIGraphicsGetCurrentContext();
    
                    NSString *imageName = @"custom_image.png";                
                    CGRect contextRect = CGRectMake(0, 0, 42.0, 42.0);
                    CGFloat fontSize = 14.0;        
    
                    [[UIImage imageNamed:imageName] drawInRect:contextRect];
    
                    NSInteger myIntegerValue = [associatedAnnotation.dataObject.myIntegerValue integerValue];
                    NSString *myStringText = [NSString stringWithFormat:@"%d", myIntegerValue];
    
                    UIFont *font = [UIFont fontWithName:@"Helvetica-Bold" size:fontSize];
    
                    CGSize fontWidth = [myStringText sizeWithFont:font];
    
                    CGFloat yOffset = (contextRect.size.height - fontWidth.height) / 2.0;
                    CGFloat xOffset = (contextRect.size.width - fontWidth.width) / 2.0;        
    
                    CGPoint textPoint = CGPointMake(contextRect.origin.x + xOffset, contextRect.origin.y + yOffset);        
    
                    CGContextSetTextDrawingMode(context, kCGTextStroke);
    
                    CGContextSetLineWidth(context, fontSize/10);
                    CGContextSetStrokeColorWithColor(context, [[UIColor whiteColor] CGColor]);
                    [myStringText drawAtPoint:textPoint withFont:font];
    
                    CGContextSetTextDrawingMode(context, kCGTextFill);
                    CGContextSetFillColorWithColor(context, [[UIColor blackColor] CGColor]);
                    [myStringText drawAtPoint:textPoint withFont:font];
    
    
                }
            }