
在A(yíng)ndroid開(kāi)發(fā)中,域內我們經(jīng)常需要實(shí)現截圖功能,實(shí)現而不僅僅是矩截圖整個(gè)屏幕的截圖,我們只需要截取屏幕上的形區某一部分,例如一個(gè)矩形區域,域內如何在A(yíng)ndroid中實(shí)現矩形區域內的實(shí)現截圖呢???本文將詳細介紹如何實(shí)現這一功能。
1. 獲取View的矩截圖Bitm??ap
我們需要獲取到目標矩形區域的View,然后將其轉換為Bitmap,形區這里我們可以使用以下方法:
public static Bitmap getViewBitmap(View view) { view.setDrawingCacheEnab(′?_?`)led(true); view.buildDra??wingCache(); return Bitmap.createBitmap(view.getDrawingCache());}2. 裁剪Bitmap
接下來(lái),域內我們需要對獲取到的實(shí)現Bitmap進(jìn)行裁剪,只保留目標矩形區域的矩截圖內容,這里我們可以使用以下??方??法:
public static Bitmap cropBitmap(Bitmap source,形區 int x, int y, int wid??th,?? int height) { return Bitmap.createBitmap(source, x, y, width, height);}3. 保存截圖
我(wo)們需要將裁剪后的Bitmap(′_`)保存到本地或者分享給其他應用,這里我們可以使用以下方法:
public static void saveBitmap(Bitmap bitmap,域(′?ω?`)內 String filePath) { FileOutp(╯°□°)╯︵ ┻━┻utStream fos = null; tr??y?? { fos = new FileOutputStream(filePath); bitmap.compress(Bitmap.(′?_?`)CompressFormat.PNG, 100,?? fos); } catch (FileNotFoundException e)(′?ω?`) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } }}(??ヮ?)?*:???4. 示例代碼
下面是一個(gè)完整的示例代碼,展示了如何在A(yíng)ndroid中實(shí)現矩形區域內的截圖:
public class ScreenshotUtil(°o°) { public static Bitmap getViewBitmap(View view) { vi(′?`*)ew.setDrawingCacheEnabled(true); view.buildDrawingCache(); return Bitmap.createBitmap(view.getDrawingCache(??)(′_`))??; } public static Bitmap cropBitmap(Bitmap source, int x, int y, int width??, int height) { return Bitmap.createBitmap(source, x,(╯°□°)╯ y, width, height); } public static void saveBitmap(Bitmap bitmap, String filePath) { FileOutputStream fos = null; try { fo??s = new FileOutputStream(filePath)ヽ(′ー`)ノ; bitmap.compress(Bitma(′ω`*)p.CompressFormat.PNG, 10( ?ω?)0, fos); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException?? e) { e.printStackTrace(); } } } }}使用方法:
// 獲取目標矩形區域的View(例如一個(gè)Im(′ω`*)ageView)ImageView imageView = findViewById(R.id.image_view);// 獲取View的BitmapBitm??ap sourceBitmap = Screensho??tUtil.getヾ(′?`)?Vi??ewBitm(′;д;`)ap(imageView);// 設置矩形區域的坐標和大?。▁, y, width, height)int x = 100; // 起始x坐標int y = 100; // 起始y坐標int width = 200??; // 寬度int height = 200; // 高度// 裁剪BitmapBitmap targetBitm(╬?益?)ap = ScreenshotUtil.cropBitmap(sourceBitmap,(°□°) x, y, width, height);// 保存截圖到本地(quot;/sdcard/screenshot.png")ScreenshotUtil.saveBitmap(targetBitmap, "/sdcard/??screenshot.png");