gpt4 book ai didi

ios - 如何让 UILabel 显示带轮廓的文本?

转载 作者:行者123 更新时间:2023-11-28 17:44:48 26 4
gpt4 key购买 nike

我想要的只是我的白色 UILabel 文本周围的一个像素黑色边框。

我使用下面的代码对 UILabel 进行了子类化,这些代码是我从一些无关紧要的在线示例中笨拙地拼凑而成的。它可以工作,但它非常非常慢(除了在模拟器上)而且我也无法让它将文本垂直居中(所以我暂时在最后一行硬编码了 y 值)。啊啊啊!

void 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]);
}

我只是有一种挥之不去的感觉,我忽略了一种更简单的方法来做到这一点。也许通过覆盖“drawTextInRect”,但我似乎根本无法让 drawTextInRect 屈服于我的意志,尽管我专心地盯着它并且皱着眉头。

最佳答案

我能够通过覆盖 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;

}

关于ios - 如何让 UILabel 显示带轮廓的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6598505/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com