In the iOS development process, the vertical center of a single line of text seems to be a very easy thing, directly with the following code to complete:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
@interfaceXxview:UIView @end
@implementationXxview
- (void) DrawRect: (CGRect) rect { Uifont *font = [Uifont Fontwithname:@ "Helvetica Neue" size:13]; nsdictionary *attributes = @{nsfontattributename:font, Nsforegroundcolorattributename:[uicolor Redcolor]}; nsattributedstring *title = [[Nsattributedstring alloc] Initwithstring: Attributes:attributes]; [title Drawatpoint:cgpointmake (Cgrectgetmidx (self .bounds)-title.size.width/ 2, Cgrectgetmidy (self.bounds)-title.size.height/2)]; @end |
On the OSX platform, we typically write this code like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21st 22
|
@interfaceXxview:NSView @end
@implementationXxview
- (void) DrawRect: (nsrect) Dirtyrect { [[NSColor Redcolor] set]; Nsframerect (Self. bounds); Nsfont *font = [Nsfont fontwithname:@ "Helvetica Neue" size:13]; Nsdictionary *attributes = @{nsfontattributename:font,nsforegroundcolorattributename:[nscolor RedColor]}; nsattributedstring *title = [[Nsattributedstring alloc] initwithstring:@ "My position is a little lower" attributes:attributes]; .size; Nspoint Drawpoint = Nsmakepoint (Nsmidx (self.width/2, Nsmidy (self.bounds)-txtsize.height/2); [title Drawwithrect:nsmakerect (drawpoint.x , Drawpoint.y, txtsize.width, txtsize.height ) Options:nsstringdrawinguseslinefragmentorigin]; @end |
The effect we see will be this:
This does not seem to fit the expectations, I tried to calculate the nsfont leading but still do not solve the problem, after the different font comparison, and draw out the size of the nsattributedstring obtained by the border, you can find Nsfont at the top will always have more empty areas , and not just the area occupied by the font leading.
Knowing the problem, even if you find a "curve salvation" solution, the original drawing method is improved to the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
- (void) DrawRect: (nsrect) Dirtyrect { [[NSColor Redcolor] set]; Nsframerect (Self. bounds); Nsfont *font = [Nsfont fontwithname:@ "Helvetica Neue" size:13]; Nsdictionary *attributes = @{nsfontattributename:font,nsforegroundcolorattributename:[nscolor RedColor]}; nsattributedstring *title = [[Nsattributedstring alloc] initwithstring:@ "I am the vertical center of the" Attributes:attributes "; Nssize txtsize = Title. size; Double Topgap = txtsize. Height-(font. Ascender + fabs (font.descender)); Nspoint Drawpoint = Nsmakepoint (Nsmidx (self.width/2, Nsmidy (self.bounds)-txtsize.height/2); if ([self isflipped]) Span class= "line" > Drawpoint.y-= Topgap/2; else Drawpoint.y + = Topgap /2; /span> |
We can finally get the results we expect, and support Flip mode:
Draw a single line of text vertically centered on OSX