Как сделать снимок экрана не только в Android с кодом
Я разработал приложение, которое снимает скриншот.
Но для этого требуется только снимок приложения. Я хочу сделать снимок из приложения.
Я исследовал ответы, но пока не нашел ответа.
Вот мой код.
View view = getWindow().getDecorView().getRootView();
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
saveImageToAppFolder(bitmap);
saveImagetoAppFolder - это функция, которая сохраняет изображение в папку приложения.
Это не проблема.
Есть ли способ сделать снимок экрана?
Ответы
Ответ 1
Чтобы сделать снимок экрана на экране устройства, Только если у вас есть root
вызовите двоичный файл screencap, например:
Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + Environment.getExternalStorageDirectory()+ "/img.png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor()
И чтобы загрузить этот файл в растровое изображение, используйте
public static Bitmap decodeSampledBitmapFromFile(String path,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
Ответ 2
Я не знаю, что ваш код в файле saveImageToAppFolder есть, но вы можете попробовать следующее:
Примечание: вам нужно установить фон вашего приложения/активности на прозрачный (100%).
//your code below is extractly
View view = getWindow().getDecorView().getRootView();
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
//try my code for save image file to storage
File imgFile = new File(imgPath);
FileOutputStream os = new FileOutputStream(imageFile);
int imgQuality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, imgQuality , os);
os.flush();
os.close();
Код для установки прозрачного фона:
//сначала: создайте тему xml ниже для прозрачности
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Transparent" parent="android:Theme">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:backgroundDimEnabled">false</item>
</style>
</resources>
после установки таким образом:
<activity android:name=".SampleActivity" android:theme="@style/Theme.Transparent">
</activity>
note: вы можете краснее узнать подробности здесь url: Как создать прозрачную активность на Android?
Ответ 3
Здесь вы можете захватить экран и сохранить его в своем хранилище
предоставить разрешения для создания файла во внешнем хранилище
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
И это код для активности.
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
}
Вот как вы можете захватить экран.