我只需要在白色UILabel文字周圍添加一個像素的黑色邊框。我使用以下代碼將UILabel子類化,從一些與切向相關的在線示例中我巧妙地將它們拼湊在一起。它可以工作,但是非常非常慢(除了在模擬器上),而且我也無法使其垂直居中放置文本(因此我暫時將y值硬編碼在最后一行)。?。oid ShowStringCentered(CGContextRef gc, float x, float y, const char *str) { CGContextSetTextDrawingMode(gc, kCGTextInvisible); CGContextShowTextAtPoint(gc, 0, 0, str, strlen(str)); CGPoint pt = CGContextGetTextPosition(gc); CGContextSetTextDrawingMode(gc, kCGTextFillStroke); CGContextShowTextAtPoint(gc, x - pt.x / 2, y, str, strlen(str));}- (void)drawRect:(CGRect)rect{ CGContextRef theContext = UIGraphicsGetCurrentContext(); CGRect viewBounds = self.bounds; CGContextTranslateCTM(theContext, 0, viewBounds.size.height); CGContextScaleCTM(theContext, 1, -1); CGContextSelectFont (theContext, "Helvetica", viewBounds.size.height, kCGEncodingMacRoman); CGContextSetRGBFillColor (theContext, 1, 1, 1, 1); CGContextSetRGBStrokeColor (theContext, 0, 0, 0, 1); CGContextSetLineWidth(theContext, 1.0); ShowStringCentered(theContext, rect.size.width / 2.0, 12, [[self text] cStringUsingEncoding:NSASCIIStringEncoding]);}我只是有點a愧的感覺,我正在忽略一種更簡單的方法來執行此操作。也許是通過覆蓋“ drawTextInRect”,但是盡管專心地盯著它并且真的皺著眉頭,但我似乎根本無法使drawTextInRect屈服于我的意愿。
3 回答

POPMUISE
TA貢獻1765條經驗 獲得超5個贊
我能夠通過重寫drawTextInRect來做到這一點:
- (void)drawTextInRect:(CGRect)rect {
CGSize shadowOffset = self.shadowOffset;
UIColor *textColor = self.textColor;
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(c, 1);
CGContextSetLineJoin(c, kCGLineJoinRound);
CGContextSetTextDrawingMode(c, kCGTextStroke);
self.textColor = [UIColor whiteColor];
[super drawTextInRect:rect];
CGContextSetTextDrawingMode(c, kCGTextFill);
self.textColor = textColor;
self.shadowOffset = CGSizeMake(0, 0);
[super drawTextInRect:rect];
self.shadowOffset = shadowOffset;
}
- 3 回答
- 0 關注
- 596 瀏覽
添加回答
舉報
0/150
提交
取消