diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CanvasRenderingContext2DImpl.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CanvasRenderingContext2DImpl.java index 2a1b69b30f..7afdc22418 100644 --- a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CanvasRenderingContext2DImpl.java +++ b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CanvasRenderingContext2DImpl.java @@ -121,19 +121,25 @@ public class CanvasRenderingContext2DImpl { // url is a full path started with '@assets/' public static void loadTypeface(String familyName, String url) { Context ctx = sContext.get(); + File fontTmpFile = null; if (!sTypefaceCache.containsKey(familyName)) { try { Font.Builder typeface = null; - if (url.startsWith("/")) { - typeface = new Font.Builder(url); + /// No error reported here, but font render incorrect. + // typeface = new Font.Builder(url); + /// TODO: Opt. + /// After copying to temporary location, we can load font successfully. + /// I don't know why. + fontTmpFile = CocosHelper.copyToTempFile(url, "fontFile"); + typeface = new Font.Builder(fontTmpFile); } else if (ctx != null) { final String prefix = "@assets/"; if (url.startsWith(prefix)) { url = url.substring(prefix.length()); } // TODO: 是否可以直接通过 rawfile 创建 font? - File fontTmpFile = CocosHelper.copyOutResFile(ctx, url, "fontFile"); + fontTmpFile = CocosHelper.copyOutResFile(ctx, url, "fontFile"); typeface = new Font.Builder(fontTmpFile); } diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosHelper.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosHelper.java index 96c6f60802..4c972f5caf 100644 --- a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosHelper.java +++ b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosHelper.java @@ -49,6 +49,7 @@ import ohos.vibrator.bean.VibrationPattern; import ohos.wifi.WifiDevice; import java.io.File; +import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.*; @@ -339,4 +340,27 @@ public class CocosHelper { } return fontTmpFile; } + + public static File copyToTempFile(String path, String tmpName) throws IOException { + File fontTmpFile; + FileOutputStream fontOutputStream=null; + FileInputStream fis = null; + try { + fontTmpFile = File.createTempFile(tmpName, "-tmp"); + fontOutputStream = new FileOutputStream(fontTmpFile); + fis = new FileInputStream(path); + byte[] buf = new byte[4096]; + while (fis.available() > 0) { + int readBytes = fis.read(buf, 0, 4096); + if (readBytes > 0) + fontOutputStream.write(buf, 0, readBytes); + } + } finally { + if(fontOutputStream!=null) + fontOutputStream.close(); + if(fis != null) + fis.close(); + } + return fontTmpFile; + } }