本文介紹了使用Unicode值在Android畫布上繪制表情符號的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試為我的Android應用程序創建自定義視圖。在OnDraw
函數中,我試圖使用unicode
值繪制一個emoji,但似乎不起作用。代碼如下:
public class Scale extends View {
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final static int LINE_WIDTH = 10;
...
...
@Override
protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(LINE_WIDTH);
mPaint.setColor(Color.BLUE);
...
...
//This works
canvas.drawText("My text", 0.05f*width, 0.80f*height, mPaint);
//But this does NOT draw a doughnut!!
String s = new String(Character.toChars(0x1F369)); //Doughnut
canvas.drawText(s, 0.75f*width, 0.50f*height, mPaint);
}
}
有沒有人知道這附近有沒有工作?還是我做錯了什么?
編輯[第二個問題]:通過我在下面提交的黑客攻擊,我看到emoji在TextView
上繪制的TextView
中呈現,但與正常TextView上設置的emoji相比,它們明顯枯燥,如下所示:
知道我在這里遺漏了什么嗎?
推薦答案
不管怎么說,我已經找到了一個解決這個問題的方法,我自己也不太喜歡!在這里,我創建一個Layout
(例如LinearLayout
),并添加一個包含我的表情符號的TextView
,然后在Canvas
上繪制Layout
。
public class Scale extends View {
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final LinearLayout layout;
...
...
public Scale(final Context context, ...) {
super(context);
...
...
//Initialise the layout & add a TextView with the emoji in it
layout = new LinearLayout(context);
final TextView tv = new TextView(context);
tv.setText(new String(Character.toChars(0x1F369))); //Doughnut
layout.addView(tv);
layout.measure(50, 50);
layout.layout(0, 0, 50, 50);
}
@Override
protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
...
...
canvas.translate(20, 20); //Translate if necessary
//Draw the layout on the canvas, draws a doughnut!!
layout.draw(canvas);
canvas.save();
canvas.restore();
}
}
如果有更好的解決方案,請發帖。
編輯
我認為StaticLayout是在畫布上繪制文本的更好選擇&;沒有文本/表情符號變得更單調的問題。
我修改的代碼(行數比以前少):
public class Scale extends View {
private final TextPaint tPaint = new TextPaint();
private final StaticLayout lsLayout;
...
...
public Scale(final Context context, ...) {
super(context);
...
...
//Initialise the layout & add a TextView with the emoji in it
String emoji = new String(Character.toChars(0x1F369))); //Doughnut
lsLayout = new StaticLayout(emoji, tPaint, 80, Layout.Alignment.ALIGN_CENTER, 1, 1, true);
}
@Override
protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
...
...
canvas.translate(20, 20); //Translate if necessary
//Draw the layout on the canvas, draws a doughnut as bright as the rest of the canvas!!
lsLayout.draw(canvas);
canvas.save();
canvas.restore();
}
}
這就是結果,表情符號和畫布上的其他圖形一樣明亮:
這篇關于使用Unicode值在Android畫布上繪制表情符號的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,