我使用NSAttributedString將圖像包含在字符串中。但是,如果在非整數幀上繪製圖像,圖像有時會模糊不清。NSAttributedString模糊圖像(NSTextAttachment)
我試圖確保每個NSTextAttachment的邊界是整數大小,但這似乎沒有幫助。有關如何確保它不模糊的任何提示?
查看附件截圖,第一條公共汽車不是模糊的,但第二條是。
我使用NSAttributedString將圖像包含在字符串中。但是,如果在非整數幀上繪製圖像,圖像有時會模糊不清。NSAttributedString模糊圖像(NSTextAttachment)
我試圖確保每個NSTextAttachment的邊界是整數大小,但這似乎沒有幫助。有關如何確保它不模糊的任何提示?
查看附件截圖,第一條公共汽車不是模糊的,但第二條是。
我通過在NSAttributedString上添加一個類別來解決這個問題。
基本上,您需要獲取NSTextAttachment的框架並添加其X座標的缺失小數部分以使其很好地舍入。
- (void)applyBlurrinessFixToAttachments {
[self enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, self.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
if (![value isKindOfClass:[NSTextAttachment class]]) {
return;
}
NSTextAttachment *attachment = (NSTextAttachment*)value;
CGRect bounds = attachment.bounds;
CGRect attributedStringRect = [self boundingRectForCharacterRange:range];
double integral;
double fractional = modf(attributedStringRect.origin.x, &integral);
if (fractional > 0) {
double roundedXOrigin = 1.0 - fractional;
// If X coordinate starts at 0.7, add 0.3 to it
bounds.origin.x += roundedXOrigin;
attachment.bounds = bounds;
}
}];
}
- (CGRect)boundingRectForCharacterRange:(NSRange)range {
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:self];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
[textStorage addLayoutManager:layoutManager];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX)];
textContainer.lineFragmentPadding = 0;
[layoutManager addTextContainer:textContainer];
NSRange glyphRange;
[layoutManager characterRangeForGlyphRange:range actualGlyphRange:&glyphRange];
return [layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:textContainer];
}
則可以使用下面的代碼圖像圓
UIGraphicsBeginImageContextWithOptions(CGSizeMake(14,14),NO,[UIScreen mainScreen] .scale);
-(UIImage *)makeRoundedImage:(UIImage *) image radius: (float) radius {
CALayer *imageLayer = [CALayer layer];
imageLayer.frame = CGRectMake(0, 0, 14, 14);
imageLayer.contents = (id) image.CGImage;
imageLayer.masksToBounds = YES;
imageLayer.cornerRadius = radius;
UIGraphicsBeginImageContextWithOptions(CGSizeMake(14, 14), NO, [UIScreen mainScreen].scale);
[imageLayer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return roundedImage;
}
您能否解釋代碼的工作原理和方式? – 2016-06-30 13:13:56
對於圖像大小調整,首先必須確定要縮放的目標大小 – amitg3 2016-06-30 13:44:21
如何渲染屬性字符串? ('UILabel','CATextLayer',其他) – 2014-12-04 13:35:59
這是在UILabel – gcamp 2014-12-04 16:52:01
我會嘗試與CATextLayer – gcamp 2014-12-04 16:54:21