實(shí)現(xiàn)思路:
畫圖時(shí)界面總體是一個(gè)大的View里面包含了一些其他組件践图,所以說想要把繪圖軟件的界面轉(zhuǎn)換成圖片導(dǎo)出,只需要將這個(gè)最底層的view導(dǎo)出成圖片窃肠。
實(shí)現(xiàn)方法:
1.在項(xiàng)目的邏輯層新建一個(gè)ViewToPicture.java類
2.類中實(shí)現(xiàn)如下功能:
Bitmap getBitmapFromView(View view)
傳入?yún)?shù)想要導(dǎo)出成圖片的view,返回獲取到的bitmap格式
private Bitmap getBitmapFromView(View view){
? ? ?Bitmap bitmap=null;
? ? ?try{
? ? ? ? //獲取所要的導(dǎo)出的圖片的長寬
? ? ? ? ? ?int width=view.getWidth();
? ? ? ? ? ?int height=view.getHeight();
? ? ? ? ? ?if(height&&width){
? ? ? ? ? ? ? ?//創(chuàng)建view對應(yīng)的bitmap
? ? ? ? ? ? ? ?bitmap=Bitmap.createBitmap(width, height,Bitmap.Config.ARGB_8888);
? ? ? ? ? ? ? ?Canvas canvas=new Canvas(bitmap);
? ? ? ? ? ? ? ?view.layout(0,0,width,height);
? ? ? ? ? ? ? ?view.draw(canvas);
? ? ? ? ? }
? ? ? ?}catch(Exception e){
? ? ? ? ? ? ?e.getStackTrace();
? ? ? }
? ? ? return bitmap;
}
boolean saveBitmap(Bitmap bitmap, String fileName,Context context)
將生成的bitmap保存到本地相冊
public boolean saveBitmap(Bitmap bitmap, String fileName,Context context) {
//獲取手機(jī)sd card路徑
String path = Environment.getExternalStorageDirectory().getPath();
//在sd卡中新建了一個(gè)用于存放從Dr.Mind app導(dǎo)出的圖片
File file = new File(path+"/Dr.Mind");
//將圖片轉(zhuǎn)換為jpg格式存儲
fileName=fileName+".jpg";
File[] fileList = file.listFiles();
//查找是否已經(jīng)存在該張圖片,已存在則不再存儲
for(int i=0;i<fileList.length;i++){
? ? ?if(fileName.equals(fileList[i].getName())){
? ? ? ? ? ? ? ?return false;
? ? ? }
? }
if (!file.exists()) {
? ? ?file.mkdir();
}
File imageFile = new File(file, fileName);
try {
? ? imageFile.createNewFile();
? ? FileOutputStream fos = new FileOutputStream(imageFile);
? //壓縮bimap尺寸
? ? bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
? //文件流寫入文件
? ? fos.flush();
? ? fos.close();
? ?//廣播通知系統(tǒng)相冊先慷,使得能在相冊中查看該文件夾?
? ? Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
? ? Uri uri = Uri.fromFile(file);
? ? intent.setData(uri);
? ? context.sendBroadcast(intent);
? ?} catch (FileNotFoundException e) {
? ? ?e.printStackTrace();
} catch (IOException e) {
? ? e.printStackTrace();
}
return true;
}
至此已經(jīng)完成了導(dǎo)出圖片的所有功能,只需要使用save方法來調(diào)用這兩個(gè)方法便可完成最終的導(dǎo)出功能
public boolean save(View view, String name,Context context) {
Bitmap bitmap = getBitmapFromView(view);
if(saveBitmap(bitmap, name,context)) return true;
? ? return false;
}