原文:http://www.adaiw.com/?p=147
看了阮一峰兄的 http://www.ruanyifeng.com/blog/2011/11/dice_portrait.html 骰子作画的算法, 觉得很有趣,就做了一个类似的应用,用自己的文字当做画笔来填充另外一段话, 效果如下: 算法非常简单:
1.从文字得到其图片,拿EidtText的CacheView。
12345678910111213141516171819202122232425 | public static Bitmap CaptureView(View v) { Bitmap bitmap = null; Bitmap mBitmap2 = null; View view = (View) v; if (view != null) { if (!view.isDrawingCacheEnabled()) { view.setDrawingCacheEnabled(true); } if (!view.isDrawingCacheEnabled()) { Log.e("Capture", "drawing cache not enabled"); } bitmap = view.getDrawingCache(); if (bitmap == null) { Log.e("Capture", "bitmap is null"); return null; } mBitmap2 = bitmap.copy(Bitmap.Config.RGB_565, true); view.setDrawingCacheEnabled(false); view.setDrawingCacheEnabled(true); } return mBitmap2; } |
2.将图片分成若干个区域,每个区域经过计算以后,取每个点的灰度的平均值,用1-6之间的一个整数表示,代表一个画笔的编号。
3.把输入的内容文字逐个取出画到一个绑定了Bitmap的Canvas上。
123456789101112131415 | // Draw canvas with custom brushes. Canvas canvas = new Canvas(); canvas.setBitmap(bitmap); if (meanArray != null) { for (int i = 0; i < outH; i++) { for (int j = 0; j < outW; j++) { int curBrush = meanArray[i][j]; if (curBrush != MAX_BRUSH_INDEX) { canvas.drawText(String.valueOf(mTextBrushes[getNextBrush()]), BRUSH_W * j, BRUSH_H * i, paint); } } } } |
4.将Bitmap保存为文件(/sdcard/adaiFill.png)。
1234567891011121314151617181920212223242526272829 | public static void saveBitmapToFile(Bitmap croppedImage, String outputPath) { if (croppedImage == null) { return; } Utils.log(LOG_TAG, "card w, h= " + croppedImage.getWidth() + "," + croppedImage.getHeight()); if (outputPath == null || ("").equals(outputPath)) { Utils.log("saveBitmapToFile path = ", "null"); return; } File file = new File(outputPath); if (file.exists()) { file.delete(); } FileOutputStream fos; try { fos = new FileOutputStream(file); if (fos != null) { croppedImage.compress(Bitmap.CompressFormat.PNG, 99, fos); } fos.close(); } catch (IOException e) { e.printStackTrace(); } } |
代码是开源的,见https://github.com/herbertdai/CanvasFill.git
APK 下载:http://code.google.com/p/canvas-fill/downloads/list
另外一个老兄用贝赛尔曲线也做出了类似的用文字填充的路径,不过他的工作看起来有点点复杂:http://planetclegg.com/projects/WarpingTextToSplines.html