测试flutter项目下txt库是否能正常工作,本demo测试文本测量功能。
#include<stdio.h>
#include<iostream>
#include <sstream>
#include <string>
#include "txt/font_style.h"
#include "txt/font_weight.h"
#include "txt/paragraph_builder_txt.h"
#include "txt/paragraph_txt.h"
#include "txt/placeholder_run.h"
#include "txt/typeface_font_asset_provider.h"
#include "flutter/fml/icu_util.h"
std::shared_ptr<txt::FontCollection> GetTestFontCollection() {
std::unique_ptr<txt::TypefaceFontAssetProvider> font_provider = std::make_unique<txt::TypefaceFontAssetProvider>();
font_provider->RegisterTypeface(SkTypeface::MakeFromFile("/home/client/flutter/engine/flutter/third_party/txt/third_party/fonts/Roboto-Black.ttf"));
std::shared_ptr<txt::FontCollection> collection = std::make_shared<txt::FontCollection>();
collection->SetAssetFontManager(sk_make_sp<txt::AssetFontManager>(std::move(font_provider)));
return collection;
}
void testText(){
const char* text = "Hello World Text Dialog";
auto icu_text = icu::UnicodeString::fromUTF8(text);
std::u16string u16_text(icu_text.getBuffer(), icu_text.getBuffer() + icu_text.length());
txt::ParagraphStyle paragraph_style;
txt::ParagraphBuilderTxt builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
// We must supply a font here, as the default is Arial, and we do not
// include Arial in our test fonts as it is proprietary. We want it to
// be Arial default though as it is one of the most common fonts on host
// platforms. On real devices/apps, Arial should be able to be resolved.
text_style.font_families = std::vector<std::string>(1, "Roboto");
text_style.color = SK_ColorBLACK;
builder.PushStyle(text_style);
builder.AddText(u16_text);
builder.Pop();
auto paragraph = std::unique_ptr<txt::ParagraphTxt>(
static_cast<txt::ParagraphTxt*>(builder.Build().release()));
paragraph->Layout(500);
printf("text line:%d\n",paragraph->GetLineCount());
printf("text width:%f\n",paragraph->GetLongestLine(),paragraph->GetMaxIntrinsicWidth());
}
int main(){
fml::icu::InitializeICU("icudtl.dat");
testText();
return 0;
}
输出内容:
text line:1
text width:153.554688