使用场景

截图指定组件区域

  1. "ui";
  2. ui.layout(
  3. <frame>
  4. <vertical gravity="center" id="all">
  5. <button text="截图这个按钮" id="截图" w="*" h="*" margin="0" padding="0" />
  6. </vertical>
  7. </frame>
  8. )
  9. ui.选择.on("click", function () {
  10. var path = saveImage(ui.截图, files.getSdcardPath() + "/preview.png")
  11. log(path)
  12. })
  13. importClass(android.graphics.Bitmap)
  14. importClass(android.view.View)
  15. importClass(android.graphics.Rect)
  16. importClass(java.io.FileOutputStream)
  17. importClass(android.os.Environment)
  18. // 获取状态栏高度
  19. const resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
  20. const statusBarHeight = context.getResources().getDimensionPixelSize(resourceId);
  21. /**
  22. * 生成视图的预览
  23. * @param View v 控件
  24. * @param Paht path 保存路径
  25. *
  26. * @return 视图生成失败返回false
  27. * 视图生成成功返回true
  28. */
  29. function saveImage(v, path) {
  30. let bitmap;
  31. let view = activity.getWindow().getDecorView();
  32. view.setDrawingCacheEnabled(true);
  33. view.buildDrawingCache();
  34. bitmap = view.getDrawingCache();
  35. let frame = new Rect();
  36. activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
  37. try {
  38. var location = [v.getX(), v.getY()];
  39. v.getLocationOnScreen(location);
  40. bitmap = Bitmap.createBitmap(bitmap, location[0], location[1] + statusBarHeight, v.getWidth(), v.getHeight()); //Bitmap source:要从中截图的原始位图,int x:起始x坐标,int y:起始y坐标,int width:要截的图的宽度,int height:要截的图的宽度
  41. let fout = new FileOutputStream(path);
  42. bitmap.compress(Bitmap.CompressFormat.PNG, 100, fout);
  43. return true;
  44. } catch (e) {
  45. // e.printStackTrace();
  46. console.error("生成预览图片失败:" + e);
  47. } finally {
  48. // 清理缓存
  49. view.destroyDrawingCache();
  50. }
  51. return false;
  52. }