Talk Mobile Support

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Monday, 18 November 2013

Android Volley の NetworkImageView で Bitmap の最大サイズを指定する

Posted on 17:24 by Unknown
Volley の NetworkImageView は便利なのですが、Bitmap のサイズを最適化してくれません。

NetworkImageView で画像のダウンロードを開始するのが loadImageIfNecessary() です。

https://android.googlesource.com/platform/frameworks/volley/+/master/src/com/android/volley/toolbox/NetworkImageView.java public class NetworkImageView extends ImageView { ... /** Local copy of the ImageLoader. */ private ImageLoader mImageLoader; ... public void setImageUrl(String url, ImageLoader imageLoader) { mUrl = url; mImageLoader = imageLoader; // The URL has potentially changed. See if we need to load it. loadImageIfNecessary(false); } ... /** * Loads the image for the view if it isn't already loaded. * @param isInLayoutPass True if this was invoked from a layout pass, false otherwise. */ private void loadImageIfNecessary(final boolean isInLayoutPass) { ... // The pre-existing content of this view didn't match the current URL. Load the new image // from the network. ImageContainer newContainer = mImageLoader.get(mUrl, new ImageListener() { @Override public void onErrorResponse(VolleyError error) { if (mErrorImageId != 0) { setImageResource(mErrorImageId); } } @Override public void onResponse(final ImageContainer response, boolean isImmediate) { // If this was an immediate response that was delivered inside of a layout // pass do not set the image immediately as it will trigger a requestLayout // inside of a layout. Instead, defer setting the image by posting back to // the main thread. if (isImmediate && isInLayoutPass) { post(new Runnable() { @Override public void run() { onResponse(response, false); } }); return; } if (response.getBitmap() != null) { setImageBitmap(response.getBitmap()); } else if (mDefaultImageId != 0) { setImageResource(mDefaultImageId); } } }); // update the ImageContainer to be the new bitmap container. mImageContainer = newContainer; } ... } ここで ImageLoader の get(url, imageListener) を呼んでいます。
ImageLoader には引数が4つの get(url, imageLoader, maxWidth, maxHeight) もあり、引数が2つの get() を呼んだ場合は、maxWidth, maxHeight には 0 が渡され、生成される Bitmap は実際の画像サイズになります。 public class ImageLoader { ... public ImageContainer get(String requestUrl, final ImageListener listener) { return get(requestUrl, listener, 0, 0); } public ImageContainer get(String requestUrl, ImageListener imageListener, int maxWidth, int maxHeight) { // only fulfill requests that were initiated from the main thread. throwIfNotOnMainThread(); final String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight); // Try to look up the request in the cache of remote images. Bitmap cachedBitmap = mCache.getBitmap(cacheKey); if (cachedBitmap != null) { // Return the cached bitmap. ImageContainer container = new ImageContainer(cachedBitmap, requestUrl, null, null); imageListener.onResponse(container, true); return container; } // The bitmap did not exist in the cache, fetch it! ImageContainer imageContainer = new ImageContainer(null, requestUrl, cacheKey, imageListener); // Update the caller to let them know that they should use the default bitmap. imageListener.onResponse(imageContainer, true); // Check to see if a request is already in-flight. BatchedImageRequest request = mInFlightRequests.get(cacheKey); if (request != null) { // If it is, add this request to the list of listeners. request.addContainer(imageContainer); return imageContainer; } // The request is not already in flight. Send the new request to the network and // track it. Request<?> newRequest = new ImageRequest(requestUrl, new Listener<Bitmap>() { @Override public void onResponse(Bitmap response) { onGetImageSuccess(cacheKey, response); } }, maxWidth, maxHeight, Config.RGB_565, new ErrorListener() { @Override public void onErrorResponse(VolleyError error) { onGetImageError(cacheKey, error); } }); mRequestQueue.add(newRequest); mInFlightRequests.put(cacheKey, new BatchedImageRequest(newRequest, imageContainer)); return imageContainer; } } maxWidth と maxHeight は ImageRequest のコンストラクタに渡されています。 public class ImageRequest extends Request<Bitmap> { ... private final int mMaxWidth; private final int mMaxHeight; ... public ImageRequest(String url, Response.Listener<Bitmap> listener, int maxWidth, int maxHeight, Config decodeConfig, Response.ErrorListener errorListener) { super(Method.GET, url, errorListener); setRetryPolicy( new DefaultRetryPolicy(IMAGE_TIMEOUT_MS, IMAGE_MAX_RETRIES, IMAGE_BACKOFF_MULT)); mListener = listener; mDecodeConfig = decodeConfig; mMaxWidth = maxWidth; mMaxHeight = maxHeight; } ... /** * The real guts of parseNetworkResponse. Broken out for readability. */ private Response<Bitmap> doParse(NetworkResponse response) { byte[] data = response.data; BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); Bitmap bitmap = null; if (mMaxWidth == 0 && mMaxHeight == 0) { decodeOptions.inPreferredConfig = mDecodeConfig; bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions); } else { // If we have to resize this image, first get the natural bounds. decodeOptions.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions); int actualWidth = decodeOptions.outWidth; int actualHeight = decodeOptions.outHeight; // Then compute the dimensions we would ideally like to decode to. int desiredWidth = getResizedDimension(mMaxWidth, mMaxHeight, actualWidth, actualHeight); int desiredHeight = getResizedDimension(mMaxHeight, mMaxWidth, actualHeight, actualWidth); // Decode to the nearest power of two scaling factor. decodeOptions.inJustDecodeBounds = false; // TODO(ficus): Do we need this or is it okay since API 8 doesn't support it? // decodeOptions.inPreferQualityOverSpeed = PREFER_QUALITY_OVER_SPEED; decodeOptions.inSampleSize = findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight); Bitmap tempBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions); // If necessary, scale down to the maximal acceptable size. if (tempBitmap != null && (tempBitmap.getWidth() > desiredWidth || tempBitmap.getHeight() > desiredHeight)) { bitmap = Bitmap.createScaledBitmap(tempBitmap, desiredWidth, desiredHeight, true); tempBitmap.recycle(); } else { bitmap = tempBitmap; } } if (bitmap == null) { return Response.error(new ParseError(response)); } else { return Response.success(bitmap, HttpHeaderParser.parseCacheHeaders(response)); } } } ImageRequest の doParse() で、mMaxWidth == 0 && mMaxHeight == 0 のときはバイト配列をそのまま Bitmap にしているのがわかりますね。
それ以外のときは BitmapFactory.Options の inJustDecodeBounds や inSampleSize を使って Bitmap をスケールしています。

以下では、View のサイズがわかっている場合はそのサイズを使い、わからないときは画面サイズを指定するようにしてみました。 public class NetworkImageView extends ImageView { ... private void loadImageIfNecessary(final boolean isInLayoutPass) { int width = getWidth(); int height = getHeight(); ... DisplayMetrics metrics = getResources().getDisplayMetrics(); int w = width > 0 ? width : metrics.widthPixels; int h = height > 0 ? height : metrics.heightPixels; // The pre-existing content of this view didn't match the current URL. Load the new image // from the network. ImageContainer newContainer = mImageLoader.get(mUrl, new ImageListener() { @Override public void onErrorResponse(VolleyError error) { if (mErrorImageId != 0) { setImageResource(mErrorImageId); } } @Override public void onResponse(final ImageContainer response, boolean isImmediate) { // If this was an immediate response that was delivered inside of a layout // pass do not set the image immediately as it will trigger a requestLayout // inside of a layout. Instead, defer setting the image by posting back to // the main thread. if (isImmediate && isInLayoutPass) { post(new Runnable() { @Override public void run() { onResponse(response, false); } }); return; } if (response.getBitmap() != null) { setImageBitmap(response.getBitmap()); } else if (mDefaultImageId != 0) { setImageResource(mDefaultImageId); } } }, w, h); // update the ImageContainer to be the new bitmap container. mImageContainer = newContainer; } }



Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Posted in Android, volley | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • Symphony Xplorer W82
    Symphony Xplorer W82 Key Features:- Operating System: Android 4.2.2 Jelly Bean 5"  TFT Capacitive Full Touch FWVGA Dispaly Camera: 5MP+...
  • #ChasingGrammers with @mnf_ For more photos and videos from the...
    instagram.com/p/ejsOTxErX0/#mnf_ instagram.com/p/ernV6hifrB/#tangerine_yin instagram.com/p/expmpmkrf8/#mnf_ instagram.com/p/fc-SoikrT3/#mnf_...
  • PPT On TRAINING OF Students Graduates
    Download TRAINING OF Students Graduates Presentation Transcript: 1.TRAINING OF students graduates 2.The problems that exist among students ...
  • Android 4.4 KitKat to be on board Moto G at Launch
    Motorola took the wraps off the Moto G earlier this week. The new budget friendly Android device from Motorola. For those of you who are ...
  • Nokia Lumia 1520 UK pricing detailed
    The Nokia Lumia 1520 has already went on sale in France and the device will soon be available in the United Kingdom. The 6-inch phablet from...
  • Google Translate App for Android Redesigned
    Google Translate app for Android wants us to be even easier to translate languages ​​from our devices, and that is why it will come the new...
  • مشاكل بالجملة تظهر في اكس بوكس ون يوم إطلاقه للبيع
    لم تنقضي 24 ساعة على بدء إطلاق جهاز إكس بوكس ون للبيع رسمياً في 13 دولة حول العالم أمس الجمعة حتى بدأت الشكاوي بالظهور من المستخدمين عن مش...
  • Samsung debuts Galaxy Grand 2 for ‘selective regions’
    Samsung on Monday introduced its latest Android smartphone, the Galaxy Grand 2, moderately sized device with mid-range specifications. Power...
  • Samsung Follows HTC’s Lead, Makes Samsung Galaxy S4 Google Play Edition Android 4.4 Files Available
    We haven’t heard that much about the Android 4.4 KitKat update to the Samsung Galaxy S4 Google Play Edition lately, though we always assu...
  • Samsung announces Galaxy Grand 2
    Samsung has announced the Galaxy Grand 2 smartphone, that comes with several improvements over its predecessor. To start off, it features a ...

Categories

  • An Organization Strategic Plan
  • And G-Zip Mega Review: Probably The Best Speakers On The Market At These Prices Android Police - Android News
  • And Light Switch Review: Good Luck Getting Them To Work Right Android Police - Android News
  • Android
  • Android App
  • Android Guys
  • AndroidGuys
  • AndroidSpin
  • Anomaly 2 Review: An Incredible Game With A Few Bugs To Hammer Out Android Police - Android News
  • Apps
  • Ardroid | أردرويد
  • Asus Transformer Pad TF701T Review: Premium Specs
  • Belkin WeMo Motion
  • Black Berry
  • Blog Portal
  • Budget Battery Life Android Police - Android News
  • Creative Advertising
  • Education in Palestine
  • Espresso
  • Factors that Increase Insurance Customer Satisfaction in Palestine
  • Featured Articles
  • Financial Analysis for PalTel
  • Floating Airport
  • Fraudulent Financial Statement
  • G-Grip
  • G-Pop
  • G-Project G-Go
  • Games
  • Google Chrome Blog
  • Gsmarena
  • GSMArena.com - Latest articles
  • HTC Blog
  • INDUSTRY ANALYSIS
  • Innovation In Advertising
  • Inside BlackBerry
  • Instagram Blog
  • INVESTMENTS
  • iphone Apple - Support - Most Recent - iPhone
  • Laws of Supply and Demand
  • LG QuickCover For Nexus 5 Quick Look: A Solid Case That Just Isnt Exciting Enough To Justify Its Price Android Police - Android News
  • Livestock Project
  • MANAGEMENT ASSERTIONS
  • MARKETING IN THE GLOBAL COMMUNITY
  • Methods of Financial Statement Fraud
  • Mobile
  • mockito
  • Money Saving
  • Non Controlling Interest
  • Not for Profit Environment
  • nvidia
  • Official LinkedIn Blog
  • Official Nexus 5 Bumper Case Quick Look: A Distinctive Cover For Your Nexus 5 With Less-Than-Perfect Buttons Android Police - Android News
  • OUTSOURCING
  • PALESTINIAN CITIES
  • PALESTINIAN OLIVE TREES
  • PAYROLL AND FIXED ASSETS MANAGEMENT
  • PC Utility
  • Phones
  • Porter’s 5 Forces
  • Premium Price
  • Productivity
  • ReVIEW
  • RHA MA750 Headphones Review: My Favorite Budget Earbuds Get A Serious Premium Counterpart Android Police - Android News
  • SFAS 116 and 117
  • Statement of Retained Earnings
  • Subsidiary Financial Statements
  • Switch
  • Symphony
  • Tablets » Reviews
  • Test
  • The Importance of Intellectual Property
  • The Official Google Blog
  • Tools
  • Toshiba Excite 7 Review: Theres Really No Reason This Tablet Should Even Exist Android Police - Android News
  • TRAINING OF Students Graduates
  • TYPES OF BUDGETS
  • TYPES OF CONTROLS
  • TYPES OF MARKETING
  • Vehicles
  • volley
  • Water Industry
  • Ways to Save Money
  • WiFi Software
  • WindowsObserver.com
  • البوابة العربية للأخبار التقنية
  • التقنية بلا حدود
  • عالم التقنية

Blog Archive

  • ▼  2013 (500)
    • ▼  November (500)
      • Symphony Xplorer W82
      • WP to put pressure on iOS in enterprise market
      • Symphony Xplorer W80
      • طريقة عمل “روت” لأجهزة نيكسوس 5 في ويندوز
      • قاموس إنكليزي-فرنسي لأجهزة “آي فون”
      • Symphony Xplorer W65
      • BlackBerry says goodbye to its COO, CMO and CFO
      • موقع لإنشاء العروض التقديمية بكل سهولة
      • موقع للبحث عن جميع المواقع المتخصصة في موضوع معين
      • تطبيق للتحكم بأجهزة آندرويد من خلال حركة الرأس أو ...
      • HTC One Google Play Edition is latest to score KitKat
      • إضافة لتسريع تصفح الإنترنت على فايرفوكس
      • تطبيق لإزالة حركات التشكيل وتعديل النصوص المزخرفة ...
      • ألمانيا تحظر على مسؤوليها استخدام الآيفون
      • Samsung debuts Galaxy Grand 2 for ‘selective regions’
      • مواقع للحصول على خلفيات شاشة عالية الدقة لأجهزة “آ...
      • نصائح إريك شميدت للانتقال “ببساطة” من آيفون إلى هو...
      • الشبكة الاجتماعية للأصوات Bubbly تجري محادثات استح...
      • خدمة التراسل الفوري “لاين” تعلن عن 300 مليون مستخد...
      • تسريب قائمة بأسماء هواتف جالاكسي القادم إليها أندر...
      • Bubbly تجري مفاوضات استحواذ مع عدة مشترين
      • “إتش تي سي” تكشف عن نسخة من “إتش تي سي ون” باللون ...
      • iPhone thief returns contact list to owner
      • HTC One رسمياً باللون الذهبي على خطى iPhone 5S
      • مايكروسوفت تؤكد دمج إصدارات ويندوز 9 وخفض عددها
      • لاين يشعل المنافسة مع الواتساب ويصل إلى 300 مليون ...
      • “آبل” تستحوذ على شركة PrimeSense المطورة لمستشعر “...
      • HTC One GPE getting Android 4.4 KitKat
      • تحديثات SkyDrive الجديدة لنظام iOS7 تتيح رفع الصور...
      • أبل تستحوذ على PrimeSense
      • Mass-market HTC One in Gold goes official
      • Better Late Than Never, Right? Gold HTC One Is Off...
      • Likely HTC One successor scores high on AnTuTu
      • Samsung Follows HTC’s Lead, Makes Samsung Galaxy S...
      • “سامسونج” تطلق “جالاكسي نوت 10.1″ (إصدار 2014) في ...
      • HTC Drops HTC One Google Play Edition Kernel Sourc...
      • صور ومواصفات سامسونج جالاكسي جراند 2
      • Samsung announces Galaxy Grand 2
      • Want Kevin Hart To Give You Driving Directions? Wa...
      • #ChasingGrammers with @mnf_ For more photos and vi...
      • مايكروسوفت تدرس إمكانية دمج نظامي “ويندوز آر تي” و...
      • تسريبات: وكالة الامن القومي الامريكية اخترقت 50 أل...
      • The Week on Instagram | 106 News Instagram blog: I...
      • لوميا 1020 يصرع الكاميرات الغير ذكية عبر التايكفوتو
      • “نوكيا” و”إل جي” و”سوني” مستمرون في سوق الحواسب ال...
      • Alcatel Idol X+ pictures and specs surface
      • In Los Angeles, Audi, Mini, BMW Meld High Tech Wit...
      • طريقة عرض/إخفاء شريط المواقع المفضلة في جوجل كروم
      • Symphony Xplorer W32
      • Symphony Xplorer W16
      • Formula One Season Finale at Interlagos To tune in...
      • Symphony Xplorer W15
      • تطبيق لبيع وشراء السلع على “آي فون” في الوطن العربي
      • عرض حالة الطقس في محرك بحث جوجل
      • متصفح لحماية المستخدم من التجسس والتتبّع في ويندوز
      • طريقة سهلة لمتابعة عدد الزوار لرابط معين
      • Amazon updates its Appstore to version 7
      • محرك بحث عن المستندات بلاحقة “PDF”
      • عرض معادلة أي خليّة في برنامج “إكسل”
      • موقع لمشاهدة تصاميم الشعارات المسروقة حول العالم
      • Xbox One Master Voice Command List
      • لأول مرة بعد تولّي تشين القيادة: بلاك بيري تعلن عن...
      • وكالة الأمن القومي الأمريكية تملك أبوابا خلفية في ...
      • Windows Phone outsells iOS in Latin America
      • [LEAK] Document Suggests Android 4.4 For Samsung D...
      • ملفات تحديث Nexus 10 لنسخة أندرويد 4.4 الأخيرة (KR...
      • إطلاق الهاتف الإماراتي الذكي “Be” يوم غد الاثنين ف...
      • مايكروسوفت تدرس إطلاق إصدار جديد من “إكس بوكس وان”...
      • اختبار سقوط هاتف LG G Flex (فيديو)
      • إطلاق ساعة Pine الذكية الداعمة لشرائح الاتصالات في...
      • مشاكل بالجملة تظهر في اكس بوكس ون يوم إطلاقه للبيع
      • موتورولا تستخدم “الطباعة ثُلاثية الأبعاد” لصنع هات...
      • Local lens: Exploring London’s East End with...
      • Xbox One Support Forums Tips and Tidbits
      • “جوجل” تُحدِّث تطبيق شبكتها الاجتماعية لنظام “آي أ...
      • أوبونتو 14.04 LTS قادمة بأيقونات جديدة .. مذهلة
      • Red Sony Xperia Z1 spotted running KitKat
      • تويتر تطبق طريقة تشفير جديدة على مواقعها
      • تطبيق قوقل بلس يدرج ترجمة المنشورات والتعليقات على...
      • انستغرام ستقدم الرسائل الخاصة قبل نهاية العام [شائ...
      • أبل تطلق إصدار آيفون 5 إس المفتوح دون تعاقد شركات ...
      • إكس بوكس ون يبيع مليون جهاز في أقل من 24 ساعة
      • The ManDroid Show: Galaxy S5 Going Metal?! Sony Wa...
      • Unleash Your Creativity With HTC Scribble
      • Weekend Hashtag Project: #WHPselfportrait Weekend ...
      • فيسبوك تختبر تصميمًا جديدًا لتطبيق شبكتها الاجتماع...
      • تسريبات تُظهر موعد وصول أندرويد 4.4 إلى أبرز أجهزة...
      • تقرير: فيسبوك تعتزم إضافة “الرسائل الخاصة” إلى إنس...
      • Motorola and 3D Systems team up to build the Ara m...
      • Leaked doc tips Android 4.4 plans for select Samsu...
      • Photographing New York City from Above with @wrong...
      • Asus Transformer Pad TF701T Review: Premium Specs,...
      • Apple iPad mini 2 review: Moving up the ranks
      • سوني تعمل على تطوير.. الباروكة الذكية!
      • Step Back: The Power of Perspective In Your First Job
      • بنترست تتيح تثبيت المواقع الجغرافية لتنظيم الرحلات
      • “فايبر” تطلق تطبيقها لنظام “لينوكس”
      • تسرب صورة الإطار المعدني الداخلي لهاتف جالاكسي إس 5
      • هل هذا هو الإطار المعدني لهاتف جالاكسي إس 5؟
      • تقرير: “إل جي” تختبر معالجاتها الخاصة بها
Powered by Blogger.

About Me

Unknown
View my complete profile