Android拍摄截图

时间:2015-12-17 12:44:19

标签: android bitmap screenshot

您好我尝试编写一个截屏的功能。 我找到了一个代码,通过按钮clicklistner完美地完成它,但当我删除按钮clicklistner并尝试在oncreate中截取我获得的位图是空的。 为什么会这样?

布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/LinearLayout01"
>
<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="munch"
    android:id="@+id/munchscreen"
    />
<ImageView
    android:layout_width="fill_parent"
    android:layout_height="500dp"
    android:id="@+id/screenshots"

    />

的活动:

public class MainActivity extends Activity {
    LinearLayout L1;
    ImageView image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);


        L1 = (LinearLayout) findViewById(R.id.LinearLayout01);
        Button but = (Button) findViewById(R.id.munchscreen);
        but.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                View v1 = L1.getRootView();
                v1.setDrawingCacheEnabled(true);
                Bitmap bm = v1.getDrawingCache();
                BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
                image = (ImageView) findViewById(R.id.screenshots);
                image.setBackgroundDrawable(bitmapDrawable);
            }
        });

    }


}

2 个答案:

答案 0 :(得分:3)

  

只是尝试在oncreate中截取我得到的位图是空的。为什么会这样?

UI尚未呈现。鉴于您正在使用的方法,您需要框架在捕获屏幕截图之前实际绘制UI。

相反,如果您将identity_map View提供给draw()支持的Bitmap,那么可能已经在{{ 1}}。这取决于是否已使用CanvasonCreate()调用了根View,而且我不确定这是否已在measure()或稍后发生。

答案 1 :(得分:0)

你可以试试这个。     公共类MainActivity扩展Activity {     LinearLayout L1;     ImageView图像;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);


    L1 = (LinearLayout) findViewById(R.id.LinearLayout01);
    Button but = (Button) findViewById(R.id.munchscreen);
    /*but.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            View v1 = L1.getRootView();
            v1.setDrawingCacheEnabled(true);
            Bitmap bm = v1.getDrawingCache();
            BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
            image = (ImageView) findViewById(R.id.screenshots);
            image.setBackgroundDrawable(bitmapDrawable);
        }
    });*/
}
  @Override
 public void onPostCreate()
 {
  View v1 = L1.getRootView();
            v1.setDrawingCacheEnabled(true);
            Bitmap bm = v1.getDrawingCache();
            BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
            image = (ImageView) findViewById(R.id.screenshots);
            image.setBackgroundDrawable(bitmapDrawable);
 }



}
相关问题