android canvas 绘制bitmap并保存到本地
16lz
2021-01-26
自定义一个view,重载draw方法(不是重载ondraw,不然图片保存下来是空白的。)在activity里面findviewbyid找到view,用view调用draw方法。
在activity的oncreate里面:
if (mBackgroundBitmap == null) { mBackgroundBitmap = Bitmap.createBitmap(screenWidth, screenHeight, Bitmap.Config.RGB_565); canvas = new Canvas(mBackgroundBitmap); } myView.draw(canvas);
自定义的myView(extend View)里面,
@Override public void draw(Canvas canvas) {//canvas.drawLine().....}
保存到本地:
activity里面一些方法,
public Bitmap getBitmap() { Bitmap whiteBgBitmap = Bitmap.createBitmap(mBackgroundBitmap.getWidth(), mBackgroundBitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(whiteBgBitmap); canvas.drawColor(Color.WHITE); canvas.drawBitmap(mBackgroundBitmap, 0, 0, null); return whiteBgBitmap; }
public boolean addGraphToGallery(Bitmap bmp) { boolean result = false; try { File photo = new File(getAlbumStorageDir("cece"), String.format("cece_bitmap_%d.jpg", System.currentTimeMillis())); saveBitmapToJPG(bmp, photo); Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri contentUri = Uri.fromFile(photo); mediaScanIntent.setData(contentUri); SpiderNetActivity.this.sendBroadcast(mediaScanIntent); result = true; } catch (IOException e) { e.printStackTrace(); } return result; }
public void saveBitmapToJPG(Bitmap bitmap, File photo) throws IOException { Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(newBitmap); canvas.drawColor(Color.WHITE); canvas.drawBitmap(bitmap, 0, 0, null); OutputStream stream = new FileOutputStream(photo); newBitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream); stream.close(); }
public File getAlbumStorageDir(String albumName) { // Get the directory for the user's public pictures directory. File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), albumName); if (!file.mkdirs()) { Log.e("SignaturePad", "Directory not created"); } return file; }
开始保存: Bitmap spiderNetBitmap = getBitmap();if (addGraphToGallery(spiderNetBitmap)) { Toast.makeText(SpiderNetActivity.this, "Spider graph saved into the Gallery", Toast.LENGTH_SHORT) .show(); } else { Toast.makeText(SpiderNetActivity.this, "Unable to store Spider graph", Toast.LENGTH_SHORT).show(); }
不要忘记在manifest里面添加存储权限:
public byte[] Bitmap2Bytes(Bitmap bm) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); }
更多相关文章
- android中重要知识点
- Android(安卓)高效加载大图片避免OOM
- android中基本的加密方法
- Activiy或者Fragment 销毁时,Dialog 的正确Dismiss方式和测试方法
- 【Tech-Android-View】Android4.0的横竖屏变动
- Android获取目录
- Android(安卓)NDK之 ----- Java 方法映射到C中的签名
- PopupWindow简单实现
- Android(安卓)TTS学习——保存对你的喜欢