gpt4 book ai didi

iphone - Core Text/NSStringDrawing - CFAttributedStringRef/NSAttributedString - 更改字体大小

转载 作者:行者123 更新时间:2023-12-03 20:48:46 24 4
gpt4 key购买 nike

案例:属性字符串已创建。如何改变字符串的大小?

我猜我们可以

A) 更新属性字符串中所有字体的 pointSize

B)通过一些变换绘制属性字符串

最佳答案

我已经用下面的代码让它工作了。但有一个问题是,如果属性字符串中的某些文本尚未设置字体属性,则它将不会更新。所以我必须用字体属性封装所有内容。

- (void)recalculateSizeChangeInAttributedString {

if(self.attributedStringOriginal == nil) {
self.attributedStringOriginal = [self.attributedString copy];
}

CFMutableAttributedStringRef tempString = CFAttributedStringCreateMutableCopy(CFAllocatorGetDefault(), self.attributedStringOriginal.length, (CFMutableAttributedStringRef)self.attributedStringOriginal);

int lastIndex = 0;
int limit = CFAttributedStringGetLength(tempString);
for (int index = 0; index < limit;) {

CFRange inRange = CFRangeMake(0, limit - index);
CFRange longestEffective;
CTFontRef font = (CTFontRef)CFAttributedStringGetAttribute(tempString, index, kCTFontAttributeName, &longestEffective);

if(font != nil) {

// log for testing
NSLog(@"index: %i, range: %i - %i, longest: %i - %i, attribute: %@",
index, inRange.location,
inRange.location + inRange.length,
longestEffective.location, longestEffective.location + longestEffective.length,
@"..."
);


// alter the font and set the altered font/attribute
int rangeEnd = longestEffective.length != 0 ? longestEffective.length : 1;
CTFontRef modifiedFont = CTFontCreateCopyWithAttributes(font, CTFontGetSize((CTFontRef)font) * sizeFactor, NULL, NULL);
CFAttributedStringSetAttribute(tempString, CFRangeMake(index, rangeEnd), kCTFontAttributeName, modifiedFont);
CFRelease(modifiedFont);

}

// make next loop continue where current attribute ended
index += longestEffective.length;

if(index == lastIndex)
index ++;
lastIndex = index;

}

self.attributedString = (NSMutableAttributedString *)tempString;

CFRelease(tempString);

}

关于iphone - Core Text/NSStringDrawing - CFAttributedStringRef/NSAttributedString - 更改字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3238493/

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