我想使用 drawText()
将单个 unicode 字符绘制到 Canvas 上。
canvas.drawText("\u270c\ufe0e", x, y, paint);
在运行 Android 7 的测试设备上,它正确显示:
但在我的模拟器中,“运行”Android 6,而在运行 Android 6 的真实设备上,它被绘制为表情符号,而不管 \ufe0e
:
这当然不是我想要的,因为我想把它画成黑色,而不是粉红色!有什么方法可以在绘制文本时“关闭”表情符号吗?
最佳答案
您可以尝试使用 EmojiCompat 库,描述 here和 here .将其添加到您的依赖项中;
dependencies {
...
implementation "com.android.support:support-emoji:27.1.1"
implementation "com.android.support:support-emoji-bundled:27.1.1"
...
}
初始化库;
EmojiCompat.init(new BundledEmojiCompatConfig(this).setReplaceAll(true));
然后将 TextView
替换为 EmojiTextView
。这是您可以用来测试的示例:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:ignore="HardcodedText">
<!-- replace -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:text="TextView - default: \u270c, text: \u270c\ufe0e, emoji: \u270c\ufe0f"/>
<!-- with -->
<android.support.text.emoji.widget.EmojiTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:text="EmojiTextView - default: \u270c, text: \u270c\ufe0e, emoji: \u270c\ufe0f"/>
</LinearLayout>
如果它不能按您希望的方式工作,请从初始化行中删除 .setReplaceAll(true)
,再试一次,看看它是否有效。
编辑:
如果您想手动绘制表情符号文本,例如到 Canvas ,您可以使用 EmojiCompat.process(...)
和 android.text.StaticLayout
来完成。我还没有尝试过,所以可能有错误,但应该可以。
// assuming x, y, and paint are defined
CharSequence emoji = EmojiCompat.get().process("\u270c\ufe0e");
StaticLayout layout = new StaticLayout(emoji, paint,
canvas.getWidth(), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
canvas.translate(x, y);
layout.draw(canvas);
canvas.translate(-x, -y);
关于android - 防止字符被绘制为表情符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50756645/