這裡說的占位符,實際就是排版時需要展示的圖片,圖片基於占位符填充,那麼處理圖片時,怎麼解決占位符(圖片)的上下偏移在設置占位符屬性時,我通過以下方法來實現它: + (NSAttributedString *)wxImageAttributeCoreTextFromPaperQuestion:(WXT ...
這裡說的占位符,實際就是排版時需要展示的圖片,圖片基於占位符填充,那麼處理圖片時,怎麼解決占位符(圖片)的上下偏移
在設置占位符屬性時,我通過以下方法來實現它:
+ (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 = 占位符(圖片)高度即可