简体   繁体   中英

Showing NSAttributedString at the Center With NSView

I have the following function to make an attributed string.

- (NSMutableAttributedString *)makeText:(NSString *)txt : (NSString *)fontname : (CGFloat)tsize :(NSColor *)textColor :(NSColor *)shadowColor :(NSSize)offset {
    NSShadow *shadow = [[NSShadow alloc] init];
    shadow.shadowColor = shadowColor;
    shadow.shadowOffset = offset;

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 10.0f;
    paragraphStyle.alignment = NSCenterTextAlignment;

    NSMutableAttributedString *atext = [[NSMutableAttributedString alloc] initWithString:txt];
    NSRange range = NSMakeRange(0,txt.length);

    // alignment
    [atext addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0,[atext length])];

    ...
    ...
    return atext;
}

If I set this attributed string to NSTextField, the resulting attributed string will be aligned correctly. But if I send it to NSView's subclass, the string will be left-aligned. Is there any way by which I can display this attributed string with correct alignment?

// .h
@interface imageView1 : NSView {
    NSAttributedString *aStr;
}

// .m
- (void)drawRect:(NSRect)dirtyRect {
    [aStr drawAtPoint:NSMakePoint((self.frame.size.width-aStr.size.width)/2.0f,(self.frame.size.height-aStr.size.height)/2.0f)];
}

Thank you for your help. The OS version is 10.8.

If you draw at a point there are no bounds in relation to which to center. You need to specify a rect. See the docs on drawWithRect:options: . Note the admonition there pointing out that to be in that rect your options will need to be (or include) NSStringDrawingUsesLineFragmentOrigin .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM