Android image loading: Using universalimageloader to load circular rounded corner Images

Source: Internet
Author: User

Android image loading: Using universalimageloader to load circular rounded corner Images
Preface

In other words, this universalimageloader is familiar with image loading because it has been used for Android for two years. That is, a newbie to Android and Baidu will have a lot of things, today, why do we need to talk about universalimageloader. First, this is really a good thing. Second, let's use imageloader to learn how to load a circular rounded corner image. 3. Direct copy may be used in future projects.
The download path on GITHUB is: https://github.com/nostra13/Android-Universal-Image-Loader, download the latest library file, and import to the project LIB can be used. Download the local library and DEMO:
:

A Brief Introduction to universalimageloader:

We can see that the general process of loading images by UIL is to determine whether there is a corresponding Bitmap in the memory, determine whether a disk exists. If not, load it from the network. Finally, determine whether Bitmap needs to be cached to the memory or disk based on the original configuration in UIL. After a Bitmap is loaded, it is parsed and displayed in a specific ImageView.

Universalimageloader use Step 1: add to Warehouse
1. Download the jar package and put it in the libs folder. 2. Maven dependency:

      
   
    com.nostra13.universalimageloader
       universal-image-loader    
   
    1.9.3
   
  

3. Gradle dependency:

compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.3'
Step 2: configure the Configuration File Permissions

  
   
  
Step 3: configure the ImageLoaderConfiguration Parameter

Configure the ImageLoaderConfiguration parameter in the application (this parameter can only be configured once. If it is configured multiple times, the first configuration parameter is used by default)

File cacheDir = StorageUtils. getCacheDirectory (context); // cache folder path ImageLoaderConfiguration config = new ImageLoaderConfiguration. builder (context ). memoryCacheExtraOptions (480,800) // default = device screen dimensions maximum length and width of the memory cache file. diskCacheExtraOptions (480,800, null) // detailed information of the local cache (maximum length and width of the cache), it is best not to set this. taskExecutor (...). taskExecutorForCachedImages (...). threadPoolSize (3) // Number of threads loaded in the default thread pool. threadPriority (Thread. NORM_PRIORITY-2) // default specifies the priority of the current thread. tasksProcessingOrder (QueueProcessingType. FIFO) // default. denyCacheImageMultipleSizesInMemory (). memoryCache (new LruMemoryCache (2*1024*1024) // you can use your own memory cache. memoryCacheSize (2*1024*1024) // maximum value of the memory cache. memoryCacheSizePercentage (13) // default. diskCache (new UnlimitedDiscCache (cacheDir) // default allows you to customize the cache path. diskCacheSize (50*1024*1024) // maximum cached value of 50 Mb SD card (local. diskCacheFileCount (100) // number of files that can be cached // default indicates that UIL is encrypted and named using HASHCODE. MD5 (new Md5FileNameGenerator () can also be used. diskCacheFileNameGenerator (new HashCodeFileNameGenerator ()). imageDownloader (new BaseImageDownloader (context) // default. imageDecoder (new BaseImageDecoder () // default. defaultDisplayImageOptions (DisplayImageOptions. createSimple () // default. discCache (new LimitedAgeDiscCache (cacheDir, 7*24*60*60) // customize the cache path. The cache is automatically cleared 7 days later. writeDebugLogs () // print the debug log. build (); // start building

Configuration parameters are even configured. Of course, you can configure them as needed, but they must be configured before initialization. In order not to perform multiple configurations, we put them in the application.

Step 4: Initialize imageLoder

ImageLoader. getInstance (). init (config); // Initialization

Step 5: imageLoder displays the option Configuration
Options = new DisplayImageOptions. builder (). showStubImage (R. drawable. ic_stub) // the image in the buffer process. showImageForEmptyUri (R. mipmap. ic_launcher) // sets the image to be displayed when the image Uri is null or incorrect. showImageOnFail (R. drawable. ic_error) // sets the picture that is incorrectly displayed during image loading or decoding. cacheInMemory (true) // cache path memory. cacheOnDisc (true) // cache to the hard disk. bitmapConfig (Bitmap. config. ARGB_8888) // sets the image decoding type. build ();

In the previous code, we set image processing and cache processing during the loading and display process.

Then use ImageLoader. getInstance (). displayImage (url, imagview, options );
We set the. displayer attribute to generate various image shapes.

Universalimageloader loads a circular image

So here is a custom circular display control:

Import android. graphics. bitmap; import android. graphics. bitmapShader; import android. graphics. canvas; import android. graphics. colorFilter; import android. graphics. matrix; import android. graphics. paint; import android. graphics. pixelFormat; import android. graphics. rect; import android. graphics. rectF; import android. graphics. shader; import android. graphics. drawable. drawable; import com. nostra13.universalimageloader. core. assist. loadedFrom; import com. nostra13.universalimageloader. core. display. roundedBitmapDisplayer; import com. nostra13.universalimageloader. core. imageaware. imageAware;/*** Created by zengyu on 2016/3/2. */public class Displayer extends RoundedBitmapDisplayer {public Displayer (int cornerRadiusPixels) {super (Inline) ;}// display Bitmap @ Override public void display (bitmap Bitmap, ImageAware imageAware, LoadedFrom loadedFrom) {imageAware. extends (new CircleDrawable (bitmap, margin);} public static class CircleDrawable extends Drawable {private final int margin; private final RectF mRect = new RectF (); private final BitmapShader bitmapShader; private final Paint paint; private RectF mBitmapRect; public CircleDrawable (Bitmap bitmap, int margin) {this. margin = 0; // create the colorant bitmapShader = new BitmapShader (bitmap, Shader. tileMode. CLAMP, Shader. tileMode. CLAMP); mBitmapRect = new RectF (margin, margin, bitmap. getWidth ()-margin, bitmap. getHeight ()-margin); // set paint to new Paint (); paint. setAntiAlias (true); paint. setShader (bitmapShader);} // circle, overwrite the original bitmap @ Override protected void onBoundsChange (Rect bounds) {super. onBoundsChange (bounds); mRect. set (margin, margin, bounds. width ()-margin, bounds. height ()-margin); // adjust the bitmap to set this Matrix. Convert the shading between the source rectangle and the destination rectangle Matrix shaderMatrix = new Matrix (); shaderMatrix. setRectToRect (mBitmapRect, mRect, Matrix. scaleToFit. FILL); // you can specify bitmapShader as the color matrix. setLocalMatrix (shaderMatrix);} // draw its border (by setting setBounds) @ Override public void draw (Canvas canvas) {Canvas. drawRoundRect (mRect, mRect. width ()/2, mRect. height ()/2, paint);}/*** returns the opacity/transparency of the drawn object. The returned value is one of the pixelformats of the abstract format constant: Unknown, translucent, transparent or opaque ** // @ Override public int getOpacity () {// translucent return PixelFormat. TRANSLUCENT;} // sets the transparency @ Override public void setAlpha (int alpha) {paint. setAlpha (alpha);} // color filter (by setting setColorFilter) @ Override public void setColorFilter (ColorFilter cf) {paint. setColorFilter (cf );}}}

All the basic usage is finished.

Import android. graphics. bitmap; import android. OS. bundle; import android. support. v7.app. appCompatActivity; import android. widget. imageView; import com. nostra13.universalimageloader. core. displayImageOptions; import com. nostra13.universalimageloader. core. imageLoader; import com. nostra13.universalimageloader. core. display. roundedBitmapDisplayer; import butterknife. butterKnife; import butterknife. injectView; public class MainActivity extends AppCompatActivity {@ InjectView (R. id. iv_normal) ImageView ivNormal; @ InjectView (R. id. iv_fillet) ImageView ivFillet; @ InjectView (R. id. iv_circular) ImageView ivCircular; private DisplayImageOptions options1, options2, options3; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); ButterKnife. inject (this); // options1 = new DisplayImageOptions in the source image. builder (). showStubImage (R. drawable. ic_stub ). showImageForEmptyUri (R. mipmap. ic_launcher ). showImageOnFail (R. drawable. ic_error ). cacheInMemory (true ). cacheOnDisc (true ). bitmapConfig (Bitmap. config. ARGB_8888) // sets the image decoding type. build (); // rounded corner image options2 = new DisplayImageOptions. builder (). showStubImage (R. drawable. ic_stub ). showImageForEmptyUri (R. mipmap. ic_launcher ). showImageOnFail (R. drawable. ic_error ). cacheInMemory (true ). cacheOnDisc (true ). bitmapConfig (Bitmap. config. ARGB_8888) // sets the image decoding type. displayer (new RoundedBitmapDisplayer (20 )). build (); // round image options3 = new DisplayImageOptions. builder (). showStubImage (R. drawable. ic_stub ). showImageForEmptyUri (R. mipmap. ic_launcher ). showImageOnFail (R. drawable. ic_error ). cacheInMemory (true ). cacheOnDisc (true ). bitmapConfig (Bitmap. config. ARGB_8888) // sets the image decoding type. displayer (new Displayer (0 )). build (); ImageLoader. getInstance (). displayImage ("http://img.my.csdn.net/uploads/201309/01/1378037193_1286.jpg", ivNormal, options1); ImageLoader. getInstance (). displayImage ("http://img.my.csdn.net/uploads/201309/01/1378037193_1286.jpg", ivFillet, options2); ImageLoader. getInstance (). displayImage ("http://img.my.csdn.net/uploads/201309/01/1378037193_1286.jpg", ivCircular, options3 );}}

Iv. Notes

1. ImageLoader determines the image width and height based on the height and width of the ImageView.
2. You must initialize ImageLoaderConfiguration. Otherwise, an error will be reported.
3. After the cache is enabled, it will be cached to the external SD card by default.
4. Clear Cache <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCgk8cHJlIGNsYXNzPQ = "brush: java;"> Public void onClearMemoryClick (View view) {ImageLoader. getInstance (). clearMemoryCache (); // clear memory cache} public void onClearDiskClick (View view) {ImageLoader. getInstance (). clearDiskCache (); // clear the local cache}

Recently, the Technical Group found that the interview questions were getting deeper and deeper, and the job was getting harder and harder to find. It was time to continue learning new things.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.