“编译”Skia
国内不适合自己编译。Github 有不止一个自动构建的SKIA二进制build,涵盖多个操作系统,可直接取而用之。
推荐大名鼎鼎的JetBrains维护的仓库,地址是 https://github.com/JetBrains/skia-build。含静态库与头文件。release静态库解压出来180MB,debug解压出来一两个G。推荐直接用release版本的。
绘制中文字符串
直接用Skia的SkString就可以,无需多次转换。如果显示方框,那说明字体不对,要设置宋体。
auto pFace = SkTypeface::MakeFromName("宋体", SkFontStyle::Normal());
SkFont font;
font.setTypeface(pFace);SkString string("加载图片 #");canvas->drawString(string, 1, 28, font, textpaint);
完整代码见文末的demo
加载并显示PNG图片等
百度“Skia绘制图片”出来的结果大多已经过时。
最新方法,要用 SkCodec::MakeFromData 解析二进制流,得到SkCodec 与 SkImageInfo,中SkImageInfo包括图片尺寸信息,然后再解码为 SkBitmap。
DWORD fileLength;char* memFile;... 加载文件到 memFile数组中sk_sp<SkData> data = SkData::MakeWithoutCopy(memFile, fileLength);auto codec = SkCodec::MakeFromData(data);if (!codec) {LogIs(2, "FAILED DECODING FILE!");}SkImageInfo codecInfo = codec->getInfo();auto alphaType = codecInfo.isOpaque() ? kOpaque_SkAlphaType : kPremul_SkAlphaType;auto decodeInfo = SkImageInfo::Make(codecInfo.width(), codecInfo.height(), kN32_SkColorType, alphaType);SkBitmap* skBitmap = new SkBitmap();char* pixels = new char[codecInfo.width()*codecInfo.height()*32];skBitmap->setInfo(decodeInfo, codecInfo.width()*32);skBitmap->setPixels(pixels);auto decodeResult = codec->getPixels(decodeInfo, pixels, codecInfo.width()*32);
decodeResult 等于零代表成功,其他可能的数值:
/*** Error codes for various SkCodec methods.*/enum Result {/*** General return value for success.*/kSuccess, 0/*** The input is incomplete. A partial image was generated.*/kIncompleteInput, 1/*** Like kIncompleteInput, except the input had an error.** If returned from an incremental decode, decoding cannot continue,* even with more data.*/kErrorInInput, 2/*** The generator cannot convert to match the request, ignoring* dimensions.*/kInvalidConversion, 3/*** The generator cannot scale to requested size.*/kInvalidScale, 4/*** Parameters (besides info) are invalid. e.g. NULL pixels, rowBytes* too small, etc.*/kInvalidParameters, 5/*** The input did not contain a valid image.*/kInvalidInput, 6/*** Fulfilling this request requires rewinding the input, which is not* supported for this input.*/kCouldNotRewind, 7/*** An internal error, such as OOM.*/kInternalError, 8/*** This method is not implemented by this codec.* FIXME: Perhaps this should be kUnsupported?*/kUnimplemented, 9};
完整 Demo 代码 | 我的Skia测试盒子
运行:
参考资料:《调用Skia内置位图编解码器的坑点》