将webview转换为位图

时间:2015-12-28 08:53:11

标签: android webview bitmap

我尝试使用某些HTML代码加载webview,然后将其捕获并转换为Bitmap。但是,我在ImageView中看到的所有测试它都是一个空方块。

webViewToPrint.loadDataWithBaseURL("", dataStringHtml , "text/html", "UTF-8", "");
webViewToPrint.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
              super.onPageFinished(view, url);

              Bitmap b = Bitmap.createBitmap( view.getHeight(), view.getWidth(), Config.ARGB_8888);
              Canvas canvas = new Canvas( b );
              view.draw(canvas);
              imageView.setImageBitmap(b);       
        }});

3 个答案:

答案 0 :(得分:1)

 webViewToPrint.setWebViewClient(new WebViewClient()
    {
            public void onPageFinished(WebView view, String url)
            {
                    Picture picture = view.capturePicture();
                    Bitmap  b = Bitmap.createBitmap( picture.getWidth(),
                    picture.getHeight(), Bitmap.Config.ARGB_8888);
                    Canvas c = new Canvas( b );
                    picture.draw( c );
                    imageView.setImageBitmap(b);    }}   

答案 1 :(得分:1)

谢谢你们的帮助。难以解决的问题是在onPageFinished中添加另一个线程(postDelayed)有一些延迟(在我的情况下500工作正常)。

答案 2 :(得分:0)

使用以下代码:

Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
imageView.setImageBitmap(bitmap);

在onPageFinished()

public Date getStartDate() 
    {

            int weekNo = findWeekOfTheYear(new Date());
            int year = findYear();
            startDate = findStartDateUsingWeekAndYear(year, weekNo);        

             return startDate;
    }

public int findYear()
     {   
         Calendar calendar = new GregorianCalendar();

          int year= calendar.get(Calendar.YEAR);

         return year;
     }

public int findWeekOfTheYear(Date date)
     {
         Calendar calendar = Calendar.getInstance();
         calendar.setTime(date);

          int weekOfMonth= calendar.get(Calendar.WEEK_OF_YEAR);

         return weekOfMonth;
     }

public Date findStartDateUsingWeekAndYear(int year,int week)
     {

         Calendar calendar = Calendar.getInstance();
         calendar.clear();
         calendar.set(Calendar.WEEK_OF_YEAR, week);
         calendar.set(Calendar.YEAR, year);

         // Now get the first day of week.
         Date date = calendar.getTime();

         return date;
     }