Взятие "скриншотов" определенного макета в Android
У меня есть две основные проблемы, которые тесно связаны. Я рассматриваю эти проблемы с программной точки зрения.
(1). Я хочу сделать снимок экрана содержания SPECIFIC, т.е. A ScrollView
, вложенного в LinearLayout
.
(2) - Как ScrollView
имеет контент, который выливается из экрана (следовательно, прокрутка стала возможной), как я могу убедиться, что на скриншоте есть элементы, которые не видны на экране?
Это текущий блок кода, который я использую. Это делает снимок экрана, но только для всего экрана. Это даже если R.id.boss
- это идентификатор ScrollView
, а не основной LinearLayout
.
View view = findViewById(R.id.boss);
View v = view.getRootView();// this does not seem to make a difference
v.setDrawingCacheEnabled(true);
v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
v.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(u.getDrawingCache());
v.setDrawingCacheEnabled(false);
Спасибо заранее.
EDIT:
Я сделал несколько ошибок. Я использовал R.id.boss
, который является неправильным ресурсом. Теперь я могу сделать снимок экрана только прокрутки, за исключением деталей вне экрана.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/boss"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="top"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="F"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Analyze via image URL"
android:textAppearance="?android:attr/textAppearanceSmall" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<EditText
android:id="@+id/mUrl"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.7"
android:text="http://" >
<requestFocus />
</EditText>
<ImageView
android:id="@+id/call"
android:layout_width="75dp"
android:layout_height="50dp"
android:layout_weight="0.3"
android:text="ABC"
android:src="@drawable/run" />
</LinearLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="ABC"
android:textAppearance="?android:attr/textAppearanceSmall" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<EditText
android:id="@+id/filepath"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.55" />
<ImageView
android:id="@+id/cam"
android:layout_width="75dp"
android:layout_height="50dp"
android:layout_weight="0.15"
android:src="@drawable/cam" />
<ImageView
android:id="@+id/browse"
android:layout_width="75dp"
android:layout_height="50dp"
android:layout_weight="0.15"
android:src="@drawable/folder"
android:text="B" />
<ImageView
android:id="@+id/upload"
android:layout_width="75dp"
android:layout_height="50dp"
android:layout_weight="0.15"
android:src="@drawable/run"
android:text="A" />
</LinearLayout>
<LinearLayout
android:id="@+id/baba"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ScrollView
android:id="@+id/scroll"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:layout_weight="0.7" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="186dp"
android:orientation="vertical" >
<ImageView
android:id="@+id/pic"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Facial recognition"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/text3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/avmarwe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Gender and age"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/skahasd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Expression and mood"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/dsfsfs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Celebrity Facial Match"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/text4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</ScrollView>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom" >
<Button
android:id="@+id/c"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_weight="0.7"
android:text="" />
<Button
android:id="@+id/share"
android:layout_width="70dp"
android:layout_height="50dp"
android:layout_weight="0.3"
android:text="" />
</LinearLayout>
</LinearLayout>
Ответы
Ответ 1
Спасибо вам, ребята, я наконец выяснил, что не так.
View v = view.getRootView();
не следует использовать, потому что он вызовет корневой режим, который я не хочу. Я ошибочно считал, что это не имеет значения, потому что я ввел неверный идентификатор ресурса.
MeasureSpec
как-то не очень хорошо рассказывал о ширине и высоте. Поэтому я использовал другой метод:
...
ScrollView z = (ScrollView) findViewById(R.id.scroll);
int totalHeight = z.getChildAt(0).getHeight();
int totalWidth = z.getChildAt(0).getWidth();
u.layout(0, 0, totalWidth, totalHeight);
...
Поскольку общая высота ScrollView может быть определена единственным дочерним элементом, который он имеет.
После внесения этих изменений теперь я могу сделать снимок экрана вложенного ScrollView и все его содержимое, видимое или нет. Для всех, кого это интересует, вот блок кода, включающий сохранение растрового изображения:
View u = findViewById(R.id.scroll);
u.setDrawingCacheEnabled(true);
ScrollView z = (ScrollView) findViewById(R.id.scroll);
int totalHeight = z.getChildAt(0).getHeight();
int totalWidth = z.getChildAt(0).getWidth();
u.layout(0, 0, totalWidth, totalHeight);
u.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(u.getDrawingCache());
u.setDrawingCacheEnabled(false);
//Save bitmap
String extr = Environment.getExternalStorageDirectory().toString() + File.separator + "Folder";
String fileName = new SimpleDateFormat("yyyyMMddhhmm'_report.jpg'").format(new Date());
File myPath = new File(extr, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
MediaStore.Images.Media.insertImage(getContentResolver(), b, "Screen", "screen");
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Ответ 2
EDIT: после просмотра комментария OP
Вам вообще не нужно думать о новых действиях. Скажите, что вы сейчас находитесь в Управлении. Макет A - это основной макет для работы, Layout B и C - это два дочерних макета внутри Layout A. Подобным образом
Layout A -> Parent
|
-------Layout B
|
-------Layout C
Теперь, если вы хотите сделать снимок экрана только с C
1) в onCreate() активности
LinearLayout myCLayout = (LinearLayout)this.findViewbyId(R.id.my_c_layout);
ViewTreeObserver vto = myCLayout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
//fully drawn, no need of listener anymore
myCLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
getDrawingBitmap();
}
});
где getDrawingBitmap() - это функция..., чтобы сделать снимок экрана.
public void getDrawingBitmap(){
LinearLayout myCLayout = (LinearLayout)this.findViewbyId(R.id.my_c_layout);
Bitmap b = myCLayout.getDrawingCache();
File file = saveBitmapAsFile(b);
}
EDIT: для ScrollView
Я никогда не пробовал. Но я думаю, вы можете это сделать.
1) сначала переопределить scrollView и переопределить функцию onMeasure.
public class MyScrollView extends ScrollView{
public MyScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(widthMeasureSpec, yourFullScrollViewHeight));
}
}
и используйте MyScrollView в своем макете.. здесь yourFullScrollViewHeight - это высота всего содержимого прокрутки, которое вам нужно сделать снимок экрана.. Я никогда не пробовал это. Но это может сработать.
Ответ 3
попробуй это, он отлично работает для меня
TableLayout tabLayout = (TableLayout) findViewById(R.id.allview);
if (tabLayout != null) {
Bitmap image = Bitmap.createBitmap(tabLayout.getWidth(),
tabLayout.getHeight(), Config.ARGB_8888);
Canvas b = new Canvas(image);
tabLayout.draw(b);
}
Ответ 4
Вот точное решение, которое вы хотите. Он отобразит весь экран, включая контент, скрытый в вашем ScrollView
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
FrameLayout root = (FrameLayout) inflater.inflate(R.layout.activity_main, null); // activity_main is UI(xml) file we used in our Activity class. FrameLayout is root view of my UI(xml) file.
root.setDrawingCacheEnabled(true);
Bitmap bitmap = getBitmapFromView(this.getWindow().findViewById(R.id.frameLayout)); // here give id of our root layout (here its my FrameLayout id)
Отобразите bitmap
в своем ImageView
или используйте его так, как вы хотите.
Наслаждайтесь..
Ответ 5
У меня также была эта проблема и она сама была закодирована.
Я использовал этот код, чтобы сделать снимок экрана всего макета.
Я изменил размер списка и некоторые математические элементы.
См. следующий веб-сайт,
Ответ 6
Попробуйте этот код
public Bitmap screenShot (просмотр)
{
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}