歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Android中截圖(surfaceView)源碼

總結了一個方法,實現了在Android當前Activity的截圖,本人測試確實通過了,不過有朋友說截出來的圖是黑色的,不能看。我心想,這沒有問題啊,相同的代碼我就可以執行通過,並沒有沒有在意這個問題。可是,今天我再調用那個方法時,截出來的圖部分是黑屏。我當時就郁悶了。網上的東西很全,但同時很亂。有一個大神用的是引用Linux下編譯出來的庫,又用到什麼JNI我完全不懂,貌似可以實現截屏。當時這個方法太麻煩,我看了一下覺得沒有信心,就又繼續尋找其他的方法。

我截圖出現黑屏的原因是在Activity中用到了SurfaceView控件,在XML布局中的控件可以完整的顯示出來但是有surfaceView的時候就出現黑屏了。具體原因我想的是因為在surfaceView中用線程不停的繪圖,操作太頻繁了,原來那種方法沒有辦法截出來。在surfaceView中繪圖的原理:

用另外一個Canvas對象不停的把要畫到surfaceView中的對象畫到這個額外的canvas中,再聲明一個Bitmap bitmap對象,注意這個bitmap不是你畫在surfaceView中的對象,而是你的目標對象,就是需要截的圖。你只需要這樣:Canvas canvas=new Canvas(bitmap),接著用canvas.drawBitmap(curBitmap, 0, 0, null),你就可以把當前的的要畫的到SurfaceView保存到bitmap中,然後把bitmap保存出來就可以了。PS:這只是截出來SurfaceView中圖像,如果想截取背景圖片,可以把surfaceView設置為透明。網上有很多種方法,這裡就不介紹了。

貼出網上可以運行的代碼:

menu.xml:

  <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/screenshot" android:title="@string/screenshot"></item>
</menu>

Element.java

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;

public class Element {
    private float mX;
    private float mY;

    private Bitmap mBitmap;

    public Element(Resources res, int x, int y) {
        mBitmap = BitmapFactory.decodeStream(new BufferedInputStream(res.openRawResource(R.drawable.icon)));
        mX = x - mBitmap.getWidth() / 2;
        mY = y - mBitmap.getHeight() / 2;
    }

    public void doDraw(Canvas canvas) {
        canvas.drawBitmap(mBitmap, mX, mY, null);
    }
}

Panel.java 

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Environment;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class Panel extends SurfaceView implements SurfaceHolder.Callback
{

 public static float mWidth;
 public static float mHeight;

 private ViewThread mThread;
 private ArrayList<Element> mElements = new ArrayList<Element>();
 private int mElementNumber = 0;

 private Paint mPaint = new Paint();
 private String mScreenshotPath = Environment.getExternalStorageDirectory()
   + "/droidnova";

 public Panel(Context context)
 {
  super(context);
  getHolder().addCallback(this);
  mThread = new ViewThread(this);
  mPaint.setColor(Color.WHITE);
 }

 

 @Override
 public void surfaceChanged(SurfaceHolder holder, int format, int width,
   int height)
 {
  mWidth = width;
  mHeight = height;
 }

 @Override
 public void surfaceCreated(SurfaceHolder holder)
 {
  if (!mThread.isAlive())
  {
   mThread = new ViewThread(this);
   mThread.setRunning(true);
   mThread.start();
  }
 }

 @Override
 public void surfaceDestroyed(SurfaceHolder holder)
 {
  if (mThread.isAlive())
  {
   mThread.setRunning(false);
  }
 }

 @Override
 public boolean onTouchEvent(MotionEvent event)
 {
  synchronized (mElements)
  {
   mElements.add(new Element(getResources(), (int) event.getX(),
     (int) event.getY()));
   mElementNumber = mElements.size();
  }
  return super.onTouchEvent(event);
 }

 /**
  * If called, creates a screenshot and saves it as a JPG in the folder
  * "droidnova" on the sdcard.
  */
 //在surfaceView上不停的繪圖
 public void doDraw(long elapsed, Canvas canvas)
 {
  canvas.drawColor(Color.BLACK);
  synchronized (mElements)
  {
   for (Element element : mElements)
   {
    element.doDraw(canvas);
   }
  }
  canvas.drawText("FPS: " + Math.round(1000f / elapsed) + " Elements: "
    + mElementNumber, 10, 10, mPaint);
 }
 public void saveScreenshot()
 {
  if (ensureSDCardAccess())
  {
   Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(),
     Bitmap.Config.ARGB_8888);
   Canvas canvas = new Canvas(bitmap);
   //在surfaceView上不停的繪圖
   doDraw(1, canvas);
   File file = new File(mScreenshotPath + "/"
     + System.currentTimeMillis() + ".jpg");
   FileOutputStream fos;
   try
   {
    fos = new FileOutputStream(file);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
    fos.close();
   }
   catch (FileNotFoundException e)
   {
    Log.e("Panel", "FileNotFoundException", e);
   }
   catch (IOException e)
   {
    Log.e("Panel", "IOEception", e);
   }
  }
 }

 /**
  * Helper method to ensure that the given path exists. TODO: check external
  * storage state
  */
 private boolean ensureSDCardAccess()
 {
  File file = new File(mScreenshotPath);
  if (file.exists())
  {
   return true;
  }
  else if (file.mkdirs())
  {
   return true;
  }
  return false;
 }
}

ScreenshotActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;

public class ScreenshotActivity extends Activity {
    private Panel mPanel;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mPanel = new Panel(this);
        setContentView(mPanel);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.screenshot:
                mPanel.saveScreenshot();
                break;
        }
        return true;
    }
}

ViewThread.java

import android.graphics.Canvas;
import android.view.SurfaceHolder;

public class ViewThread extends Thread {
    private Panel mPanel;
    private SurfaceHolder mHolder;
    private boolean mRun = false;
    private long mStartTime;
    private long mElapsed;
   
    public ViewThread(Panel panel) {
        mPanel = panel;
        mHolder = mPanel.getHolder();
    }
   
    public void setRunning(boolean run) {
        mRun = run;
    }
   
    @Override
    public void run() {
        Canvas canvas = null;
        mStartTime = System.currentTimeMillis();
        while (mRun) {
            canvas = mHolder.lockCanvas();
            if (canvas != null) {
                mPanel.doDraw(mElapsed, canvas);
                mElapsed = System.currentTimeMillis() - mStartTime;
                mHolder.unlockCanvasAndPost(canvas);
            }
            mStartTime = System.currentTimeMillis();
        }
    }
}

其實這很好理解。由於我的代碼寫在整個項目中,跌出來比較麻煩,就貼了一個以可以完整通過的工程。

下載地址:

下載在Linux公社的1號FTP服務器裡,下載地址:

FTP地址:ftp://www.linuxidc.com

用戶名:www.linuxidc.com

密碼:www.muu.cc

在 2012年LinuxIDC.com\7月\Android中截圖(surfaceView)源碼

下載方法見 http://www.linuxidc.net/thread-1187-1-1.html

關於截屏,暫時我的需求已經滿足了,不知道這符合其他情況麼?歡迎有興趣的人一起交流。

Copyright © Linux教程網 All Rights Reserved