簡體   English   中英

在AsyncTask中使用Picasso從URL獲取位圖

[英]Getting bitmap from URL using Picasso in AsyncTask

編輯:我已修復“方法調用...”錯誤。 現在我的主要問題實際上是從URL加載位圖。 當我嘗試使用PIcasso中的.get()方法時,我顯然無法正確處理它,並且遇到了java.lang.OutOfMemoryError

做這個的最好方式是什么? 我什至不需要整個圖像,只需要一個中心裁剪來填充設備上的牆紙即可。 但是我不能不先加載就裁剪它,這是我的問題。


因此,我嘗試使用Picasso從給定的URL獲取位圖,然后在其頂部繪制文本並將其設置為我的牆紙背景。 我目前正在嘗試從AsyncTask中的onPostExecute執行此操作。 我得到的錯誤是:

java.lang.IllegalStateException: Method call should not happen from the main thread.

導致問題的代碼行是:

Bitmap bitmap = Picasso.with(myContext)
                .load(url + ".jpg")
                .fit()
                .centerCrop()
                .get();

以及整個onPostExcute函數:

protected void onPostExecute(String url) {

    ImageView imageView = (ImageView) rootView.findViewById(R.id.preview);
    try {
        Bitmap bitmap = Picasso.with(myContext)
                .load(url + ".jpg")
                .fit()
                .centerCrop().get();

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setColor(Color.RED); //Text Color
        paint.setStrokeWidth(72); //Text Size
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER)); //Text Overlapping Pattern

        canvas.drawBitmap(bitmap, 0, 0, paint);
        canvas.drawText("Test...", 10, 10, paint);

        ((ImageView) rootView.findViewById(R.id.preview)).setImageBitmap(bitmap);
        WallpaperManager wallpaperManager = WallpaperManager.getInstance(myContext);
        //wallpaperManager.suggestDesiredDimensions(width, height);
        wallpaperManager.setBitmap(bitmap);

        Toast.makeText(myContext, "Wallpaper set successfully.", Toast.LENGTH_SHORT).show();
    }
    catch (Exception e) {
        android.util.Log.e(TAG, "Failed to set wallpaper", e);
    }
}

我什至無法測試所有的canvas / paint代碼來查看它是否有效。 如果您也發現任何錯誤,請告訴我。 任何和所有提示都將不勝感激。 謝謝。

只需將@ jayeshsolanki93和@zapl注釋放在一起。 之所以出現該錯誤,是因為您正在主線程上從Picasso調用方法get() get()是一個同步方法,因此會出錯。 您有兩種選擇:

  1. get()的調用移動到AsyncTask doInBackground方法,然后在onPostExecute上執行所有畫布操作。
  2. 充分利用Picasso的優勢,並使用已有的異步方法並執行以下操作:

     Picasso.with(context).load(url).into(new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { Log.i(TAG, "The image was obtained correctly, now you can do your canvas operation!"); } @Override public void onBitmapFailed(Drawable errorDrawable) { Log.e(TAG, "The image was not obtained"); } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { Log.(TAG, "Getting ready to get the image"); //Here you should place a loading gif in the ImageView to //while image is being obtained. } }); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM