首页 > 解决方案 > 防止字符被绘制为表情符号

问题描述

我想将单个 unicode 字符绘制到画布上,使用drawText().

canvas.drawText("\u270c\ufe0e", x, y, paint);

在运行 Android 7 的测试设备上,它正确显示:

正确绘制的字符

但是在我的模拟器中,“运行”Android 6,以及在运行 Android 6 的真实设备上,它被绘制为表情符号,无论\ufe0e

绘制为表情符号的字符

这当然不是我想要的,因为我想把它画成黑色,而不是粉红色!绘制文本时有什么方法可以“关闭”表情符号吗?

标签: androidunicodeandroid-canvasdrawemoji

解决方案


您可以尝试使用此处此处描述的 EmojiCompat 库。将其添加到您的依赖项中;

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));

然后替换TextViewEmojiTextView. 这是一个可用于测试的示例:

<?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)从初始化行中删除,再试一次,看看是否有效。

编辑:

如果您想手动将表情符号文本绘制到画布上,您可以使用EmojiCompat.process(...)and来完成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);

推荐阅读