當前位置:菜譜大全網 - 菜譜 - 知乎ios app中的圖文混排是如何實現的?是加載html嗎?

知乎ios app中的圖文混排是如何實現的?是加載html嗎?

用iOS實現圖文混合排版的兩種方法

如果妳想自定義文字的布局,比如在QQ、微信等應用中使用顏文字,妳很可能會使用CoreText,這是iOS和OSX平臺上文字處理的底層框架,可以實現任意的文字排列。更多詳情請戳官方文檔。壹般來說,我們用下面的代碼來實現圖文混排:

text =[[NSMutableAttributedString alloc]init with string:@ " "];

nsattributedstring * txt 1 =[[nsattributedstring alloc]initwithstring:@ " test "];

[text appendAttributedString:txt 1];

[txt1發布];

CTRunDelegateCallbacks回調;

callback . version = kctrundelegateversion 1;//必須指定,否則不會生效,也不會產生回調。

callback . dealloc = deallocCallback;

callback . get ascent = get ascent;

callback . get descent = get descent;

callback.getWidth = getWidth

ns dictionary * imgAttr =[[ns dictionary withobjectsandkeys:@ 100,@"width ",nil]retain];

CTRunDelegateRef delegate = CTRunDelegateCreate(& amp;回調,imgAttr);

ns dictionary * txtDelegate =[ns dictionary withobjectsandkeys:(id)delegate,(ns string *)kCTRunDelegateAttributeName,@100,@"width ",nil];

NSAttributedString * img field =[[NSAttributedString alloc]initWithString:@ " " attributes:txt delegate]auto release];

[text appendAttributedString:img field];

[text appendattributestring:[[nsattributestring alloc]initwithstring:@ " End "]auto release]];

CGMutablePathRef path ref = CGPathCreateMutable();

CGPathAddRect(pathRef,NULL,CGRectMake(0,0,self.frame.size.width,self . frame . size . height));

frame setter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)text);

CT frame = CTFramesetterCreateFrame(frame setter,CFRangeMake(0,0),pathRef,NULL);

CFArrayRef lines = CTFrameGetLines(CT frame);

CG point origins[CFArrayGetCount(lines)];

CTFrameGetLineOrigins(ctFrame,CFRangeMake(0,0),origins);

for(int I = 0;我& ltCFArrayGetCount(lines);i++) {

CTLineRef line = CFArrayGetValueAtIndex(lines,I);

CFArrayRef runs = CTLineGetGlyphRuns(line);

for(int j = 0;j & ltCFArrayGetCount(運行次數);j++) {

CTRunRef run = CFArrayGetValueAtIndex(runs,j);

CG point line origin = origins[I];

ns dictionary * meta =(ns dictionary *)CTRunGetAttributes(run);

如果(元& amp& amp([meta valueForKey:@"width"]!=零)){

image location . y = line origin . y;

CG float offset = CTLineGetOffsetForStringIndex(line,CTRunGetStringRange(run))。位置,空);

image location . x = line origin . x+offset+self . frame . origin . x;

}

}

}

cf release(path ref);

[self set needs display];

壹直以來,我都認為這是實現的唯壹途徑。嗯,其實我也沒想過有沒有其他的實現方式。直到有壹天,我看著效果差不多的代碼,驚訝地發現:為什麽沒有CTRunDelegate?於是我仔細思考了這個問題。當創建壹個CTFrame時,我將指定壹個路徑。通常我會用壹個CGRect來完成這個路徑,然後在有圖片的地方用CTRunDelegate來處理。但實際上我可以用CGMutablePath來畫壹個不規則的文本路徑,比如我可以在預定的位置畫圖,而不用用CTRunDelegate進行特殊處理。這種方法更適合於圖像位置固定的應用。

轉自馬冬生