这里说的占位符,实际就是排版时需要展示的图片,图片基于占位符填充,那么处理图片时,怎么解决占位符(图片)的上下偏移
在设置占位符属性时,我通过以下方法来实现它:
+ (NSAttributedString *)wxImageAttributeCoreTextFromPaperQuestion:(WXTKCoretextQSourceImg *)image{ CTRunDelegateCallbacks callbacks; memset(&callbacks, 0, sizeof(CTRunDelegateCallbacks)); callbacks.version = kCTRunDelegateVersion1; callbacks.getAscent = ascentCallbackPaper; callbacks.getDescent = descentCallbackPaper; callbacks.getWidth = widthCallbackPaper; CTRunDelegateRef delegate = CTRunDelegateCreate(&callbacks, (__bridge void *)(image)); // 使用0xFFFC作为空白的占位符 unichar objectReplacementChar = 0xFFFC; NSString * content = [NSString stringWithCharacters:&objectReplacementChar length:1]; NSMutableDictionary * attributes = [self wxAttributesPaperImg:image]; NSMutableAttributedString * space = [[NSMutableAttributedString alloc] initWithString:content attributes:attributes]; CFAttributedStringSetAttribute((CFMutableAttributedStringRef)space, CFRangeMake(0, 1), kCTRunDelegateAttributeName, delegate); CFRelease(delegate); return space; }
上述方法在引入 CTRunDelegateCallbacks 时,提供了控制占位符大小属性,即:getAscent、getDescent、getWidth
getWidth是占位符所取宽,getAscent与getDescent分别基于基准可上下偏移,一般情况,getDescent会提供返回0值,而getAscent一般是占位符(图片)的高度;下面通过设置不同数值,看下字符如何偏移;
向下不偏移,向上提供占位符高度
///占位基准上升度 static CGFloat ascentCallbackPaper(void *ref){ WXTKCoretextQSourceImg *refP = (__bridge WXTKCoretextQSourceImg *)ref; return refP.height; } ///占位基准下降度 static CGFloat descentCallbackPaper(void *ref){ return 0; }
视觉给我感觉默认不向下偏移,图片比左侧字符高一点点
向下偏移5,向上提供占位符高度 - 5
///占位基准上升度 static CGFloat ascentCallbackPaper(void *ref){ WXTKCoretextQSourceImg *refP = (__bridge WXTKCoretextQSourceImg *)ref; return refP.height - 5; } ///占位基准下降度 static CGFloat descentCallbackPaper(void *ref){ return 5; }
向下偏移10,向上提供占位符高度 - 10
///占位基准上升度 static CGFloat ascentCallbackPaper(void *ref){ WXTKCoretextQSourceImg *refP = (__bridge WXTKCoretextQSourceImg *)ref; return refP.height - 10; } ///占位基准下降度 static CGFloat descentCallbackPaper(void *ref){ return 10; }
向下偏移整个占位(图片)高度,向上提供占位符高度 0
///占位基准上升度 static CGFloat ascentCallbackPaper(void *ref){ WXTKCoretextQSourceImg *refP = (__bridge WXTKCoretextQSourceImg *)ref; return refP.height - refP.height; } ///占位基准下降度 static CGFloat descentCallbackPaper(void *ref){ WXTKCoretextQSourceImg *refP = (__bridge WXTKCoretextQSourceImg *)ref; return refP.height; }
注意有个问题,上述的 getAscent、getDescent值加起来,其实就是图片的高度,那么如果比高度大或者小的情况下,图片会被拉伸,或者压缩
向下偏移小于整个占位(图片)高度( -10),向上提供占位符高度 0
///占位基准上升度 static CGFloat ascentCallbackPaper(void *ref){ WXTKCoretextQSourceImg *refP = (__bridge WXTKCoretextQSourceImg *)ref; return refP.height - refP.height; } ///占位基准下降度 static CGFloat descentCallbackPaper(void *ref){ WXTKCoretextQSourceImg *refP = (__bridge WXTKCoretextQSourceImg *)ref; return refP.height - 10; }
总结
上下偏移要处理好图片的高度值,确保getAscent + getDescent = 占位符(图片)高度即可
原文链接:https://www.cnblogs.com/wangkejia/p/16892664.html
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:iOS-Coretext 图文混排占位符上下偏移处理 - Python技术站