LED顯示效果
項目地址
效果圖a
原理
廣告牌中經常能看到上面這種顯示效果,使用LED燈實現文字甚至是圖片的顯示,那如何在Android中實現這種效果呢?
通常的做法應該是獲取字體的點陣信息,然后經過計算在對應的位置繪制圓點,但是這樣太麻煩了,于是我使用了一種比較偷懶的做法,原理是這樣的:
1.首先將文字轉換為Bitmap,既得到一張跟文字顯示效果一樣的圖片;
2.按照一定的間隔點獲取該圖片中對應的像素點是否有顏色,如果有,則在該點繪制LED燈,否則不繪制。
使用這種方法的一個好處是,即便是圖片也可以輕松轉換成LED顯示。
代碼實現
Read the fucking source code!
廢話不多說,下面看看如何具體實現代碼。
1.首先我們將要顯示的文字轉換為Bitmap
private Bitmap renderText(CharSequence text, Paint paint) {
Bitmap bitmap = Bitmap.createBitmap(mDrawableWidth, mDrawableHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 2));
canvas.drawText(text.toString(),0,yPos,paint);
return bitmap;
}
2.根據LED燈的半徑和LED的間距,生成一個所有LED燈所在位置的List,這個List存儲我們計算好的所有LED燈的位置
List<Point> circlePoint = new ArrayList<>();
private void measurePoint(int width, int height) {
int halfBound = ledRadius + ledSpace / 2;
int x = halfBound;
int y = halfBound;
for (; ; ) {
for (; ; ) {
circlePoint.add(new Point(x, y));
y += halfBound * 2;
if (y > height) {
y = halfBound;
break;
}
}
x += halfBound * 2;
if (x > width) {
break;
}
}
}
3.根據已經生成的文字Bitmap和LED等的位置,生成LED圖
// 獲取Bitmap指定位置的顏色,
// 這個方法比較長,我簡化了一下,
// 詳細代碼請移步項目地址查看源碼
private int isInRange(Bitmap bitmap, int x, int y) {
...
int color = bitmap.getPixel(x - ledRadius, y);
....
return color;
}
// 根據Led等的位置和原始的TextBitmap生成LedBitmap
private Bitmap generateLedBitmap(Bitmap src) {
Bitmap bitmap = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
for (Point point : circlePoint) {
// Detect if the px is in range of our led position
int color = isInRange(src, point.x, point.y);
if (color != 0) {
canvas.drawCircle(point.x, point.y, ledRadius, paint);
}
}
return bitmap;
}
4.最后我們在onDraw()方法中將這個Bitmap繪制到Canvas中即可,有一點需要注意的是,如果這個Bitmap的尺寸超過 4 * 1024
在有的手機上會報OpenGL Texture最大尺寸不能超過4096像素的錯誤,所以在繪制的時候檢查一下Bitmap的尺寸是否超過,如果是,則將這個Bitmap拆分成多個Bitmap進行繪制。