IPhone/IOS image problems (reading, saving, drawing, and other problems)

Source: Internet
Author: User
I. Reading Images1. Read from resource
UIImage* image=[UIImage imageNamed:@"1.jpg"];

2. Read from the network

NSURL *url=[NSURL URLWithString:@"http://www.sinaimg.cn/qc/photo_auto/chezhan/2012/50/00/15/80046_950.jpg"];UIImage *imgFromUrl =[[UIImage alloc]initWithData:[NSData dataWithContentsOfURL:url]];

3. Read data locally from the mobile phone

// Read the local image not resourcensstring * apath3 = [nsstring stringwithformat: @ "% @/documents/sources @.jpg", nshomedirectory (), @ "test"]; uiimage * imgfromurl3 = [[uiimage alloc] initwithcontentsoffile: apath3]; uiimageview * imageview3 = [[uiimageview alloc] initwithimage: imgfromurl3];

4. Obtain the image from the existing context

// Add ImageIO. framework and # import <ImageIO/ImageIO. h> cgimagesourceref source = hour (cfurlref) URL, null); cgimageref IMG = hour (source, 0, null); cgcontextref CTX = uigraphicsgetcurrentcontext (); cgcontextsavegstate (CTX ); // two transformctm Methods // cgcontextconcatctm (CTX, cgaffinetransformmakescale (. 2,-0.2); // cgcontextscalectm (CTX, 1,-1); // note that the coordinates must be reversed, use CTX as the image source cgimageref capture = cgbitmapcontextcreateimage (CTX); cgcontextdrawimage (CTX, cgrectmake (160, 0,160,230), [Image cgimage]); cgcontextdrawimage (CTX, cgrectmake (160,230,160,230 ), IMG); cgimageref capture2 = cgbitmapcontextcreateimage (CTX );

5. Use cgimagesourceref of quartz to read images.

CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)url, NULL);CGImageRef img= CGImageSourceCreateImageAtIndex(source,0,NULL);
Ii. Save Images1. Convert to nsdata to save the image (imgfromurl is uiimage)
// Save the image. You can obtain both paths. // nsarray * paths = nssearchpathfordirectoriesindomains (nsdocumentdirectory, nsuserdomainmask, yes); // nsstring * documentsdirectory = [paths objectatindex: 0]; // nsstring * apath = [documentsdirectory stringbyappendingpathcomponent: [nsstring stringwithformat: @ "symbol @.jpg", @ "test"]; nsstring * apath = [nsstring stringwithformat: @ "% @/documents/Documents @.jpg", nshomedirectory (), @ "test"]; nsdata * imgdata = uiimagejpegrepresentation (imgfromurl, 0); [imgdata writetofile: apath atomically: yes];

2. Use cgimagedestinationref of quartz to output images. This method is not common, so we will not introduce it. For details, see the apple documentation quartz 2D programming guide.3. Drawing (draw | painting)1. Add the uiimageview method to the uiview layer.

UIImageView* imageView=[[UIImageView alloc]initWithImage:image];imageView.frame=CGRectMake(0, 0, 320, 480);[self addSubview:imageView];[imageView release];

2. [img drawatpoint] series of methods

[image4 drawAtPoint:CGPointMake(100, 0)];  

3. cgcontextdrawimage

CGContextDrawImage(ctx, CGRectMake(160, 0, 160, 230), [image CGImage]);

4. cglayer is an offscreen rendering method recommended by Apple, which is better than bitmapcontext because it seems to be accelerated using the iPhone hardware (drawing-card ).

Cglayerref CG = cglayercreatewithcontext (CTX, cgsizemake (320,480), null); // you need to use cglayercontext as the cache context. This is a required cgcontextref layercontext = cglayergetcontext (CG ); cgcontextdrawimage (layercontext, cgrectmake (160,230,160,230), IMG); cgcontextdrawlayeratpoint (CTX, cgpointmake (0, 0), CG );

5. Contents of calayer

UIImage* image=[UIImage imageNamed:@"1.jpg"];CALayer *ly=[CALayer layer];ly.frame=CGRectMake(0, 0, 320, 460);ly.contents=[image CGImage];[self.layer addSublayer:ly];
4. Others1. cgimage and uiimage are interchangeable so that you can switch the type between uikit and quartz at any time, and select the method you are familiar with to process the image. cgimage = [uiimage cgimage]; uiimage * uiimage = [uiimage imagewithcgimage: cgimage]; 2. the problem of uiimage resizableimagewithcapinsets is assumed that a 44x29 image, the same insets = uiedgeinsetsmake (10, 10, 10) has different performance in the @ 2X and non-@ 2x scenarios, non-@ 2x is OK, but if the image of the same size is changed to @ 2x, it will become very stuck during the transition, and it should be caused by different re-painting, on the surface, the reason is that the insets is set to point. In the case of @ 2x, the scaled pixel is actually 20 above and 20 below, but the image is actually only 29, which leads to incorrect results, set insets to = uie Dgeinsetsmake (,) is normal, so pay attention to it later. 3. Notes for using animated images

After setting the animation image, startanimation is required. The animation image is not automatically started.

In addition, this method is not suitable for reading a large number of animated images, because so many images are suddenly exposed. You can use this method instead. I did not try it either. The method is to manually switch the image, instead of directly using the system method.

imgV=[[UIImageView alloc]initWithFrame:CGRectMake(40, 40, 128, 128)];[self.window addSubview:imgV];[self performSelectorInBackground:@selector(playAnim)withObject:nil];[imgV release];-(void)playAnim{for (int i=0;i<101;){usleep(100000);UIImage *image=[[UIImage alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%d",i+1 ] ofType:@"tiff"]];[self performSelectorOnMainThread:@selector(changeImage:) withObject:image waitUntilDone:YES];i++;}} -(void)changeImage:(UIImage*)image{imgV.image=image; } 

Post: http://www.cocoachina.com/bbs/read.php? Tid = 110154

4. uicontrol set uiimage

The Problem description mainly involves a very small cross button that requires a large response to the click area. The Code is as follows:

Uiimage * BG = [uiimage imagenamed: @ "heizi1.jpg"]; // if the image is larger than the vertex and region, narrow down BG = [self scaleimage: BG tosize :( cgsize) {100,100}]; uibutton * button = [[uibutton alloc] initwithframe: cgrectmake (0, 0,200,200)]; // if the image is larger than the button, it is stretched, if the value is smaller than the button, the center displays [Button setimage: BG forstate: uicontrolstatenormal];

In addition, if you want to prepare two sets of images for this icon image, scaling will consume efficiency after all.

Image Scaling code

        -(UIImage *)scaleImage:(UIImage *)img ToSize:(CGSize)itemSize{                UIImage *i;        //    CGSize itemSize=CGSizeMake(30, 30);        UIGraphicsBeginImageContext(itemSize);        CGRect imageRect=CGRectMake(0, 0, itemSize.width, itemSize.height);        [img drawInRect:imageRect];        i=UIGraphicsGetImageFromCurrentImageContext();        UIGraphicsEndImageContext();        return i;}

From View

#import <QuartzCore/QuartzCore.h>-(UIImage *)getImageFromView:(UIView *)orgView{    UIGraphicsBeginImageContext(orgView.bounds.size);    [orgView.layer renderInContext:UIGraphicsGetCurrentContext()];    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();    UIGraphicsEndImageContext();       return image;}


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.