iOS Development Uiimageview

Source: Internet
Author: User

Less nonsense, go straight to the point!!!

1. Create a Uiimageview:

There are several ways to create a Uiimageview object:


Uiimageview *imageview2 = [[Uiimageview alloc] initWithFrame: (CGRect)]; Uiimageview *IMAGEVIEW3 = [[Uiimageview alloc] Initwithimage: (UIImage *)]; *IMAGEVIEW4 = [[Uiimageview alloc] Nitwithimage: (UIImage *) Highlightedimage: (UIImage **imageview5 = [[ Uiimageview Alloc] Initwithcoder: (Nscoder *)];

The more commonly used is the front three. As for the fourth, when the highlighted attribute of this imageview is yes, the parameter highlightedimage is displayed, and the first parameter uiimage is typically displayed.

2. Frame and Bounds properties:

The second method of creating a Uiimageview method is to set the position and size at the time of creation.

When you want to change the position later, you can reset the Frame property:

Imageview.frame = CGRectMake (CGFloat x, cgfloat y, cgfloat width, cgfloat heigth);
Imageview.bounds = CGRectMake (CGFloat x, cgfloat y, cgfloat width, cgfloat heigth);

So what's the difference between a bounds and a frame property?

Frame sets its position and size, and bounds can only set its size, and the X and y in its parameters do not work even if the frame property was not previously set, the final position of the control is not the parameter set by bounds. The bounds implementation is to scale the Uiimageview control to the center of the original center.

Consider the following example:

Imageview.frame = CGRectMake (00460= CGRectMake (  );

After execution, the position and size of this imageview are (80, 115, 160, 230).

3. Contentmode Properties:

This property is used to set the display of the image, such as centering, right, whether zooming, etc., there are several constants to set:

Uiviewcontentmodescaletofilluiviewcontentmodescaleaspectfituiviewcontentmodescaleaspectfilluiviewcontentmoderedrawuiviewc Ontentmodecenteruiviewcontentmodetopuiviewcontentmodebottomuiviewcontentmodeleftuiviewcontentmoderightuiviewcontentmodeto Pleftuiviewcontentmodetoprightuiviewcontentmodebottomleftuiviewcontentmodebottomright

Note that the above several constants, usually without scale, when the picture size exceeds imageview size, only part of the display in the ImageView.

The Uiviewcontentmodescaletofill property causes the picture to deform.

Uiviewcontentmodescaleaspectfit will ensure that the picture scale is the same, and that it all appears in ImageView, which means that ImageView will be partially blank.

Uiviewcontentmodescaleaspectfill will also be the same as the picture, but it is filled with the entire imageview, it is possible that only some of the pictures are displayed.

4. Change the location

4.1 Modify its Frame property directly

4.2 Modify its Center property:

Imageview.center = Cgpointmake (CGFloat x, cgfloat y);

The Center property refers to the middle point of the ImageView.

4.3 Using the Transform property

Imageview.transform = cgaffinetransformmaketranslation (cgfloat dx, cgfloat dy);

where dx and dy indicate how much you want to move in the X or Y direction, rather than how much to move.

5. Rotate the image

Imageview.transform = cgaffinetransformmakerotation (cgfloat angle);

Note: It rotates in a clockwise direction, and the center of the rotation is the center of the original ImageView, which is the position represented by the Center property.

The parameter of this method is angle in radians, not our most commonly used degree, so you can write a macro definition:

#define Degreestoradians (x) (m_pi* (x)/180.0)

6. Zoom image

Or use the Transform property:

Imageview.transform = Cgaffinetransformmakescale (cgfloat scale_w, CGFloat scale_h);
Wherein, CGFloat scale_w and cgfloat scale_h respectively indicate how many times the original width and height are scaled

7. Play a series of pictures

Imageview.animationimages = Imagesarray; // set the number of seconds that all pictures are played imageview.animationduration = [Imagesarray count]; // do not repeat how many times, 0 means countless times 0 ; // Start Playback [ImageView startanimating];

8. Add a click event for the Picture:

imageview.userinteractionenabled =*singletap = [[UITapGestureRecognizer alloc] Initwithtarget:self Action: @selector (Tapimageview:)]; [ImageView Addgesturerecognizer:singletap];

Be sure to set userinteractionenabled to Yes before you can respond to the click event.

9. Other Settings

Imageview.hidden = yes or no;                                   // hide or Show picture Imageview.alpha = (cgfloat) al;                                // Set Transparency imageview.highlightedimage = (UIImage *) hightlightedimage;     // set the picture displayed when highlighting Imageview.image = (UIImage *) image;                            // set up a picture for normal display [ImageView SizeToFit];                                         // resize the picture to be the same as the content picture

10, picture cache (the latest version sdwebimage use)

<1> download Sdwebimage, import project. GitHub Escrow Address Https://github.com/rs/SDWebImage

<2> Import header files where needed

" uiimageview+webcache.h "

<3> Call Sd_setimagewithurl: Method caches the picture, note that this is the new version of the new method, the old method is Setimagewithurl:.

1. Sd_setimagewithurl:

// the basic code of the picture cache is that simple [Self.image1 sd_setimagewithurl:imagepath1];

2. Sd_setimagewithurl:completed:

// block can do something after the picture is loaded [Self.image2 sd_setimagewithurl:imagepath2 completed:^ (UIImage *image, Nserror *error, Sdimagecachetype CacheType, Nsurl *ImageURL) {                 NSLog (@ " here can do something after the picture is loaded ");             }];

3. Sd_setimagewithurl:placeholderimage:

// to a default picture, first use the default picture, when the picture is loaded and then replaced [Self.image1 sd_setimagewithurl:imagepath1 placeholderimage:[uiimage imagenamed:@ "default "]];

4. Sd_setImageWithURL:placeholderImage:completed:

// Use the default picture and do something with block after it's done [Self.image1 sd_setimagewithurl:imagepath1 placeholderimage:[uiimage imagenamed:@ "default" ] completed:^ (UIImage *image, Nserror *error, Sdimagecachetype cachetype, Nsurl *ImageURL) {                 NSLog ( @" things to do after the picture is loaded " );             }];

5. Sd_setImageWithURL:placeholderImage:options:

// Options Selection Method [Self.image1 sd_setimagewithurl:imagepath1 placeholderimage:[uiimage imagenamed:@ "default" ] options:sdwebimageretryfailed];

In addition to the options option, the other method is integrated storage, that is, memory cache and disk cache in combination, if you only need memory cache, then the options here to choose Sdwebimagecachememoryonly.

Here you can already use Sdwebimage to cache the picture (over)

/**************************************************************************************************/

In-depth understanding of parts

Options All option:

     //Retry after failuresdwebimageretryfailed =1<<0,           //download begins during UI interaction, resulting in delayed downloads such as Uiscrollview deceleration. Sdwebimagelowpriority =1<<1,           //Memory Cache onlySdwebimagecachememoryonly =1<<2,           //This flag can be incrementally downloaded, and the displayed image is progressively downloaded inSdwebimageprogressivedownload =1<<3,           //Refresh Cachesdwebimagerefreshcached =1<<4,           //Background DownloadSdwebimagecontinueinbackground =1<<5,           //nsmutableurlrequest.httpshouldhandlecookies = YES;sdwebimagehandlecookies=1<<6,           //allow an invalid SSL certificate to be used//sdwebimageallowinvalidsslcertificates = 1 << 7,//Priority DownloadSdwebimagehighpriority =1<<8,           //Delay PlaceholderSdwebimagedelayplaceholder =1<<9,           //change the animated imageSdwebimagetransformanimatedimage =1<<Ten,

Sdwebimage Internal implementation Process

  1. Entry SetImageWithURL:placeholderImage:options: The Placeholderimage is displayed first, and then the Sdwebimagemanager is processed based on the URL.

  2. Enter Sdwebimagemanager-downloadwithurl:delegate:options:userinfo:, to Sdimagecache from the cache to find whether the picture has been downloaded Querydiskcacheforkey :d Elegate:userinfo:.

  3. First from the memory picture cache to find if there is a picture, if there is already a picture cache in memory, Sdimagecachedelegate callback ImageCache:didFindImage:forKey:userInfo: to Sdwebimagemanager.

  4. Sdwebimagemanagerdelegate callback Webimagemanager:didfinishwithimage: to Uiimageview+webcache and other front-end display pictures.

  5. If no memory is in the cache, the build nsinvocationoperation is added to the queue to start looking for pictures from the hard disk if it is already cached.

  6. Try to read the picture file according to Urlkey in the hard disk cache directory. This step is performed at Nsoperation, so the callback notifydelegate is returned to the main thread:.

  7. If the previous action reads a picture from the hard disk, the picture is added to the in-memory cache (if the free memory is too small, the memory cache is emptied first). Sdimagecachedelegate callback ImageCache:didFindImage:forKey:userInfo:. And then callback the display image.

  8. If the picture is not read from the hard disk cache directory, the picture is not present in all caches, the picture needs to be downloaded, and the callback ImageCache:didNotFindImageForKey:userInfo:.

  9. Share or regenerate a downloader sdwebimagedownloader start downloading pictures.

  10. Image download by nsurlconnection to do, to achieve the relevant delegate to determine the picture download, download complete and download failed.

  11. Connection:didreceivedata: The use of ImageIO to download the progress by the picture loading effect.

  12. Connectiondidfinishloading: After the data download is finished, give sdwebimagedecoder to do the image decoding processing.

  13. The image decoding process is done in a nsoperationqueue and does not slow down the main thread UI. If there is a need to download the image two times, it is best to complete here, the efficiency will be much better.

  14. In the main thread Notifydelegateonmainthreadwithinfo: announce the decoding complete, ImageDecoder:didFinishDecodingImage:userInfo: callback to Sdwebimagedownloader.

  15. Imagedownloader:didfinishwithimage: Callback to Sdwebimagemanager tell the picture download complete.

  16. Notify all downloaddelegates download complete, callback to show the image where needed.

  17. Save the picture to Sdimagecache, the memory cache and the hard disk cache are saved at the same time. Writing files to the hard disk is also done in a separate nsinvocationoperation to avoid slowing down the main thread.

  18. Sdimagecache registers some message notifications at initialization time, cleans up the memory image cache when the memory is warning or back to the background, and cleans up outdated images when the app is finished.

  19. SDWI also offers uibutton+webcache and mkannotationview+webcache for ease of use.

  20. Sdwebimageprefetcher can pre-download images for later use.

As you can see from the above process, when you call Setimagewithurl: method, he will automatically go to do so many things for you, when you need to do something at a specific time, you can override these methods. For example, in the process of downloading a picture to respond to an event, this method is overwritten:

    // The override method, which is where to hit, this method is the response    when downloading imagePath2 Sdwebimagemanager *manager = [Sdwebimagemanager Sharedmanager];         [Manager downloadimagewithurl:imagepath2 options:sdwebimageretryfailed Progress:^(Nsinteger receivedsize, Nsinteger expectedsize) {                 NSLog (@ " show Current progress ");             } Completed:^ (UIImage *image, Nserror *error, Sdimagecachetype CacheType, BOOL finished, Nsurl *ImageURL) {
    nslog (@ " Download complete ");    }];

Reprint http://my.oschina.net/plumsoft/blog/76128

Http://www.cocoachina.com/ios/20141212/10622.html

iOS Development Uiimageview

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.