- 论坛徽章:
- 0
|
WebView截屏可以直接用webView.capturePicture方法,也可以用javascript代码计算页面实际高度和宽度
package com.sunting;
import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Bitmap.Config; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout;
/** * * * @author sunting Email:ting.sun@renren-inc.com */ public class SnapShotActivity extends Activity {
private int webViewWidth;
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout linearLayout = (LinearLayout) LinearLayout.inflate(this, R.layout.main, null); setContentView(linearLayout);
Button button = (Button) findViewById(R.id.snapShot); final ImageView image = (ImageView) findViewById(R.id.image);
final WebView webView = new WebView(this); linearLayout.addView(webView); webView.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, 150)); webView.getSettings().setJavaScriptEnabled(true); webView.setSaveEnabled(true); webView.addJavascriptInterface(new JavaScriptInterface(), "HTMLOUT"); webView.loadUrl("http://www.iteye.com"); webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; }
@Override public void onPageFinished(WebView view, String url) { view.loadUrl("javascript:window.HTMLOUT.getContentWidth(document.getElementsByTagName('html')[0].scrollWidth);"); super.onPageFinished(view, url); } });
button.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // capture webview Bitmap bmp = Bitmap.createBitmap( px2dip(SnapShotActivity.this, webViewWidth), webView.getContentHeight(), Config.ARGB_8888); webView.draw(new Canvas(bmp));
image.setBackgroundDrawable(new BitmapDrawable(bmp)); } }); }
/** * helper method to change px value to dip value * * @param context * The Context the program is running in * @param pxValue * The px value * @return */ private static int px2dip(Context context, float pxValue) { float density = context.getResources().getDisplayMetrics().density; return (int) (pxValue / density + 0.5f); }
/** * helper javascript class to get webViewWidth and set it * * @author sunting Email:ting.sun@renren-inc.com */ class JavaScriptInterface { public void getContentWidth(String value) { if (value != null) { webViewWidth = Integer.parseInt(value); } } } } |
|