Skip to content

Instantly share code, notes, and snippets.

@pengan1987
Created May 30, 2017 00:00
Show Gist options
  • Select an option

  • Save pengan1987/af00f9b0d43de4a5e6e6b5d47e53d0de to your computer and use it in GitHub Desktop.

Select an option

Save pengan1987/af00f9b0d43de4a5e6e6b5d47e53d0de to your computer and use it in GitHub Desktop.
ImageHelper can convert webpage to bitmap
package com.vidao.webtoimage;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Build;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
public class ImageHelper {
private WebView webview;
public ImageHelper(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
WebView.enableSlowWholeDocumentDraw();
}
float scale = activity.getResources().getDisplayMetrics().density;
int width = Math.round(scale * 384);
webview = new WebView(activity);
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(width, 10);
layoutParams.width = width;
layoutParams.height = 10;
webview.setLayoutParams(layoutParams);
webview.measure(0, 0);
webview.layout(0, 0, width, 10);
}
public void loadWeb() {
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(true);
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) {
super.onPageFinished(view, url);
}
});
webview.loadUrl("http://m.baidu.com");
}
/**
* 获得快照
*/
public void renderBitmap() {
float scale = webview.getScale();
int webViewHeight = Math.round(webview.getContentHeight() * scale);
Bitmap bitmap = Bitmap.createBitmap(webview.getWidth(), webViewHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
webview.draw(canvas);
Log.d("Web to image:", Integer.toString(webViewHeight));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment