使用场景
截图指定组件区域
"ui";
ui.layout(
<frame>
<vertical gravity="center" id="all">
<button text="截图这个按钮" id="截图" w="*" h="*" margin="0" padding="0" />
</vertical>
</frame>
)
ui.选择.on("click", function () {
var path = saveImage(ui.截图, files.getSdcardPath() + "/preview.png")
log(path)
})
importClass(android.graphics.Bitmap)
importClass(android.view.View)
importClass(android.graphics.Rect)
importClass(java.io.FileOutputStream)
importClass(android.os.Environment)
// 获取状态栏高度
const resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
const statusBarHeight = context.getResources().getDimensionPixelSize(resourceId);
/**
* 生成视图的预览
* @param View v 控件
* @param Paht path 保存路径
*
* @return 视图生成失败返回false
* 视图生成成功返回true
*/
function saveImage(v, path) {
let bitmap;
let view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
bitmap = view.getDrawingCache();
let frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
try {
var location = [v.getX(), v.getY()];
v.getLocationOnScreen(location);
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:要截的图的宽度
let fout = new FileOutputStream(path);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fout);
return true;
} catch (e) {
// e.printStackTrace();
console.error("生成预览图片失败:" + e);
} finally {
// 清理缓存
view.destroyDrawingCache();
}
return false;
}