import ViewGroup from 'android.view.ViewGroup'; import Bitmap from 'android.graphics.Bitmap'; import View from 'android.view.View'; import FileOutputStream from 'java.io.FileOutputStream'; import File from 'java.io.File'; import Canvas from 'android.graphics.Canvas'; function savePhotoTocache(img : Bitmap) : string { let context = UTSAndroid.getAppContext()! let filepath = context.getExternalCacheDir()?.getPath() ?? "" let fileid = Math.random().toString(16).substring(2, 11); let file = new File(filepath, fileid + '.jpg'); let fos = new FileOutputStream(file) img.compress(Bitmap.CompressFormat.JPEG, 100, fos); return file.getPath() } function getScreenImage() { let decorView : ViewGroup = UTSAndroid.getUniActivity()!.window.decorView as ViewGroup let rootview : View = decorView.getRootView() // rootview.setDrawingCacheEnabled(true) // let bitmap = Bitmap.createBitmap(rootview.getDrawingCache()) // rootview.setDrawingCacheEnabled(false) let bitmap = Bitmap.createBitmap(rootview.width, rootview.height, Bitmap.Config.ARGB_8888) let canvas = new Canvas(bitmap) rootview.draw(canvas) return savePhotoTocache(bitmap); } /** * 获取窗口截图 */ export function getRootShotImage(callback : (str : string) => void) { callback(getScreenImage()) } /** * 获取指定元素截图 */ export function getElementShotImage(ele:UniElement|null, callback : (str : string) => void) { if(ele == null) { callback("") return; } let view = ele.getAndroidView() as View|null; if(view == null) { callback("") return; } let rootview = view as View; // rootview.setDrawingCacheEnabled(true) // let bitmap = Bitmap.createBitmap(rootview.getDrawingCache()) // rootview.setDrawingCacheEnabled(false) let bitmap = Bitmap.createBitmap(rootview.width, rootview.height, Bitmap.Config.ARGB_8888) let canvas = new Canvas(bitmap) rootview.draw(canvas) let imgpath:string = savePhotoTocache(bitmap); callback(imgpath) }