ios - how to set CATextLayer text vertical position? -


i create uilabel , catextlayer in app using following code

- (void)viewdidload {     [super viewdidload];     self.textlabel = [[uilabel alloc] initwithframe:cgrectmake(20, 90, 20, 20)];     self.textlabel.text = @"1";     self.textlabel.font = [uifont systemfontofsize:12];     self.textlabel.backgroundcolor = [uicolor redcolor];     [self.view addsubview:self.textlabel];      self.textlayer = [catextlayer layer];     [self.textlayer setstring:@"1"];     [self.textlayer setfont:(__bridge cftyperef)([uifont systemfontofsize:12])];     self.textlayer.backgroundcolor = [uicolor greencolor].cgcolor;     self.textlayer.frame = cgrectmake(70, 90, 50, 20);     [self.view.layer addsublayer:self.textlayer]; } 

and result is

enter image description here

the red 1 uilabel, green 1 calayer. want know how vertical align text incalayer, theuilabel` shows.

the correct answer found here in objective-c , works ios. works subclassing catextlayer , overriding drawincontext function.

however, i've made improvements code, shown below, using david hoerl's code basis. changes come solely in recalculating vertical position of text.

here code swift users:

class lctextlayer : catextlayer {  // ref: http://lists.apple.com/archives/quartz-dev/2008/aug/msg00016.html // credit: david hoerl - https://github.com/dhoerl  // usage: fix vertical alignment issue exists within catextlayer class. change made ydiff calculation.  override init!() {     super.init() }  override init!(layer: anyobject!) {     super.init(layer: layer) }  required init(coder adecoder: nscoder) {     super.init(layer: adecoder) }  override func drawincontext(ctx: cgcontext!) {     let height = self.bounds.size.height     let fontsize = self.fontsize     let ydiff = (height-fontsize)/2 - fontsize/10      cgcontextsavegstate(ctx)     cgcontexttranslatectm(ctx, 0.0, ydiff)     super.drawincontext(ctx)     cgcontextrestoregstate(ctx) } } 

Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -