本文介紹了使用Unicode值在Android畫布上繪制表情符號(hào)的處理方法,對大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我正在嘗試為我的Android應(yīng)用程序創(chuàng)建自定義視圖。在OnDraw
函數(shù)中,我試圖使用unicode
值繪制一個(gè)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);
}
}
有沒有人知道這附近有沒有工作?還是我做錯(cuò)了什么?
編輯[第二個(gè)問題]:通過我在下面提交的黑客攻擊,我看到emoji在TextView
上繪制的TextView
中呈現(xiàn),但與正常TextView上設(shè)置的emoji相比,它們明顯枯燥,如下所示:
知道我在這里遺漏了什么嗎?
推薦答案
不管怎么說,我已經(jīng)找到了一個(gè)解決這個(gè)問題的方法,我自己也不太喜歡!在這里,我創(chuàng)建一個(gè)Layout
(例如LinearLayout
),并添加一個(gè)包含我的表情符號(hào)的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();
}
}
如果有更好的解決方案,請發(fā)帖。
編輯
我認(rèn)為StaticLayout是在畫布上繪制文本的更好選擇&;沒有文本/表情符號(hào)變得更單調(diào)的問題。
我修改的代碼(行數(shù)比以前少):
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();
}
}
這就是結(jié)果,表情符號(hào)和畫布上的其他圖形一樣明亮:
這篇關(guān)于使用Unicode值在Android畫布上繪制表情符號(hào)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,