UIImageView和UIImage,CGContextRef 的一些知識點

來源:互聯網
上載者:User

1.UIImageView不支援內部圖片平鋪(tile)

2.資源中的圖片要用小寫,模擬器中可能不區分大小寫,但在真機中區分.

   [UIImage imageNamed:@""]; 在裝置中區分大小寫

3.UIView沒有背景圖屬性,有背景色屬性.設定背景圖可以用addSubView(backgroundImage);,推薦的是設定背景色。

4.[UIImage imageNamed:@""];它是有緩衝特性

   + (UIImage *)imageWithContentsOfFile:(NSString *)path;  //does not cache the image object.

   imageNamed文檔解釋:

  This method looks in the system caches for an image object
with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.

  On a device running iOS 4 or later, the behavior is identical if the device’s screen has a scale of1.0. If the screen has a scale of2.0, this method first searches for an image file with the same filename with an@2x
suffix appended to it. For example, if the file’s name isbutton, it first searches forbutton@2x. If it finds a 2x, it loads that image and sets thescale property of the returnedUIImage object to2.0.
Otherwise, it loads the unmodified filename and sets thescale property to1.0.

   On iOS 4 and later, the name of the file is not required to specify the filename extension. Prior to iOS 4, you must specify the filename extension.

    可能在多次操作之後,應用經常發生記憶體警告從而導致自動結束的問題。定位之後發現是由於[UIImage imageNamed: @""]分配的映像都沒有釋放引起的。而之前從官方的reference中得到的資訊應該是[UIImage imageNamed:@""]分配的映像系統會放到cache裡面。而關於cache管理的規則就沒有明確的介紹。由此看來[UIImage imageNamed:]只適合與UI介面中小的貼圖的讀取,而一些比較大的資源檔應該盡量避免使用這個介面。

 5. UIImage的 - (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight

     指定兩個方向上不被縮放的部分。

     對應的 rightCapWidth = image.size.width - (image.leftCapWidth + 1);

                bottomCapHeight = image.size.height - (image.topCapHeight + 1);

     leftCapWidth,rightCapWidth之間的,topCapHeight,bottomCapHeight之間的像素被平鋪以達到縮放效果。

     另外UIView.contentStretch在這裡好像不起作用。

      注意:使用這個函數時,要取它的傳回值。並且 That method could return nil if the base image is less than 5 pixels wide or 5 pixels tall
since it needs the 4 pixels for the caps + 1 pixel to stretch.

樣本:設定導覽列上的自訂返回按鈕

- (void)setNavigationBackButton{    const int KLeftWidth=25;    UIImage* image=[[UIImage imageNamed:@"back.png"] stretchableImageWithLeftCapWidth:KLeftWidth topCapHeight:0];    UIImage* hightlightedImage=[[UIImage imageNamed:@"back_pressed.png"] stretchableImageWithLeftCapWidth:KLeftWidth topCapHeight:0];    NSString* text=[[[self.navigationController viewControllers] objectAtIndex:0] navigationItem].title;    UIFont* font=[Utility fontWithSize:12];    CGSize stringSize = [text sizeWithFont:font];    CGFloat textWidth = stringSize.width+KLeftWidth;        UIButton* button=[UIViewUtil createUIButtonWithImage:image                                       hightlightedImage:hightlightedImage                                             selectedImage:nil                                                   title:text                                              titleColor:color(0x33,0x33,0x33)                                                    posX:0 posY:0];    button.titleLabel.font=[Utility fontWithSize:12];    CGRect rect=button.frame;    rect.size.width=textWidth;    button.frame=rect;    UIBarButtonItem* buttonItem = [[UIBarButtonItem alloc] initWithCustomView:button];    [button addTarget:self action:@selector(popViewControllerAnimated) forControlEvents:UIControlEventTouchUpInside];    [[self navigationItem] setLeftBarButtonItem:buttonItem];    [buttonItem release];    [button release];    }

6.支援內建動畫,播放圖片序列。

    imageView.animationImages = imageArray;    imageView.animationDuration = 0.75f;    [self.view addSubview:imageView];    [imageView startAnimating];

7.UIImageView要設定self.userInteractionEnabled = YES才支援互動。

8. 構建映像的方式:

    UIGraphicsBeginImageContext(CGSizeMake(SIDE_LENGTH, SIDE_LENGTH));//建立一個新映像上下文    CGContextRef context = UIGraphicsGetCurrentContext();    ...    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();//將上下文轉為一個UIImage對象。    UIGraphicsEndImageContext();    return theImage;

9.生動影像,如gif,貌似 iphone不支援動態圖象,採用UIWebView替代顯示gif。

   (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{            NSString* referenceURL=[info objectForKey:UIImagePickerControllerReferenceURL];        NSLog(@"%@",referenceURL);  //assets-library://asset/asset.JPG?id=1000000001&ext=JPG                ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];...}#import <AssetsLibrary/ALAssetsLibrary.h>#import <AssetsLibrary/ALAssetRepresentation.h>//http://stackoverflow.com/questions/5187251/ios-select-a-gif-from-the-photo-library-convert-to-nsdata-for-use-in-multipart

10.儲存圖片到相簿

-(void)saveToPhotosAlbum{    UIImage* image=nil;    NSObject* obj=..;    if([obj isKindOfClass:[UIImage class]])    {        image=(UIImage*)obj;    }    else    {        image=[UIImage imageWithData:(NSData *)obj];    }    if(image)    {        UIImageWriteToSavedPhotosAlbum(image,self,@selector(image:didFinishSavingWithError:contextInfo:), nil);     }    else    {         //@"儲存失敗";    }}#if 1  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo  {      if (error == nil)          //@"儲存成功";    else         //@"儲存失敗";}  #endif  

11.emoji表情

emoji是日本開發的一字元編碼集,在iOS中整合了該字元集, 可以通過編程的方式判斷,開啟或關閉該功能。

已測試它可顯示於UILabel,UIButton,UIWebView,使用如“\ue415”的unicode碼。

http://pukupi.com/post/1964/

可結合NSString的draw方法,把表情畫到UIImage上:

CGSize size = [text sizeWithFont:aFont];if (UIGraphicsBeginImageContextWithOptions != NULL){   UIGraphicsBeginImageContextWithOptions(size,NO,0.0);}else{   UIGraphicsBeginImageContext(size);}[text drawAtPoint:CGPointMake(0.0, 0.0) withFont:aFont];UIImage *image = UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();    return image;

編程開啟iOS emoji,未測試成功。
http://blog.csdn.net/favormm/article/details/6774899

iOS5.1下emoji表情顯示方框的解決辦法   

在iOS5.1的部分裝置上,emoji表情無法正常顯示.原因是iOS4上面的emoji用的是softbank的編碼,到iOS5以後,emoji被放進了Unicode6.0,導致原來的老編碼可能存在部分不相容現象.
解決辦法在iOS5上面全部用新編碼,在iOS4及以下全部用老編碼.
因為有些iOS5.1上可以正常顯示,有些不行。根據我們的測試情況,5.x的全部用新編碼,4.x及以下全部用老編碼就沒問題了
蘋果自己的轉換表: http://opensource.apple.com/source/ICU/ICU-461.13/icuSources/data/translit/Any_SoftbankSMS.txt 左邊的是Unicode新編碼,右邊是softbank的老編碼,請自行轉換

http://www.cocoachina.com/bbs/read.php?tid=96847&page=1

12.UIImagePickerController 拍照後,圖片旋轉了90度。可能這個情況在5.0就不出現了。

#pragma mark UIImagePickerControllerDelegate- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{    [picker dismissModalViewControllerAnimated:YES];        NSString* mediaType=[info objectForKey:UIImagePickerControllerMediaType];    if([mediaType isEqualToString:(NSString*)kUTTypeImage])//@"public.image"    {        UIImage* image=[info objectForKey:UIImagePickerControllerOriginalImage];        UIImageOrientation imageOrientation=image.imageOrientation;        if(imageOrientation!=UIImageOrientationUp)        {            // 原始圖片可以根據照相時的角度來顯示,但UIImage無法判定,於是出現擷取的圖片會向左轉90度的現象。            // 以下為調整圖片角度的部分            UIGraphicsBeginImageContext(image.size);            [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];            iPortraitImageView.image = UIGraphicsGetImageFromCurrentImageContext();            UIGraphicsEndImageContext();            // 調整圖片角度完畢        }    }}  //設定可編輯選取的圖片UIImagePickerController* pickerController = [[UIImagePickerController alloc] init];        pickerController.delegate = self;        pickerController.allowsEditing=YES;//設定可編輯選取的圖片        if(buttonIndex==0)        {            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])            {                pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;            }        }        else        {            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])            {                pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;            }        }                [[UIViewUtil firstAvailableUIViewControllerWithView:self] presentModalViewController:pickerController animated:YES];        [pickerController release];- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{    [picker dismissModalViewControllerAnimated:YES];        NSString* mediaType=[info objectForKey:UIImagePickerControllerMediaType];    if([mediaType isEqualToString:(NSString*)kUTTypeImage])//@"public.image"    {        UIImage* image=[info objectForKey:UIImagePickerControllerEditedImage];        iPortraitImageView.image=image;    }} 後面再次測試,結果測試每次拍照:UIImage* image=[info objectForKey:UIImagePickerControllerOriginalImage];UIImageOrientation imageOrientation=image.imageOrientation;imageOrientation的值如左列,拍照時home鍵在位置為右列的值UIImageOrientationRight 下UIImageOrientationUp    右UIImageOrientationDown  左UIImageOrientationLeft  上

若拍照多次後,出現黑屏,檢查是否有列印內容警告,同時看是否有上一次的拍照的圖片沒釋放。

13. 對nil的image.size.width取值,結果可能不確定。可能在大多數機器上取值為0,而有的機器上取到的是不確定值。

      所以一定要判斷如果為nil,width取值0。

14.用圖片填充backgroundColor時,圖片上的透明地區可能為成為黑色。backgroundColor是隨內容大小而鋪的。

 

15.在資來源目錄中,如果同時存在Icon.png 114x114像素,Icon@2x.png 114x114像素

[image imageNamed:@"Icon.png"]; //尺寸是114點,使用的圖片是Icon.png,像素/點為1:1NSString* path=[[NSBundle mainBundle ] pathForResource:@"Icon" ofType:@"png"];[UIImage imageWithContentsOfFile:path];//尺寸是114點,使用的圖片是Icon.png,像素/點為1:1path=[[NSBundle mainBundle ] pathForResource:@"Icon@2x" ofType:@"png"];UIImage imageWithContentsOfFile:path];//尺寸是57點,使用的圖片是Icon@2x.png,像素/點為2:1

在Documents中時,imageWithContentsOfFile的結果同上。

看樣子,對檔案名稱中的@2x的識別,是UIImage在根據路徑找圖片後本身完成的,並且它是看最後使用的圖片名,而不一定是在路徑中指定的。

data=[NSData dataWithContentsOfFile:path];image=[UIImage imageWithData:data];對於Icon.png和Icon@2x.png,尺寸都是114點,像素/點為1:1。

16.圖片圓角化

     http://www.cocoachina.com/bbs/read.php?tid=1757&page=1

17. 給圖片加濾鏡

      用Core Graphic的API,把圖片解析成RGBA四通道的位元影像放入記憶體, 然後記憶體中有一個數組,數組中的每四個元素都是映像上的一個像素點的RGBA的數值(0-255),改變RGB的數值,再寫回去重建。

      變為黑白照片就是把每個像素點的RGB的值相加求平均值,再回寫回去。例如:R=B=G=100,就是灰色的,寫 for迴圈把每個像素點的RGB都改成各自的平均值,照片就變為黑白色了。如果映像變為懷舊照片,就是底色發黃的,就是RG的比值調高,B保持不變,因為紅綠相配就是黃色。
      藉助Android裡的ColorMatrix(顏色矩陣)的概念,重要的就是把每個像素點的RGB調整為新值。

      http://www.cocoachina.com/bbs/read.php?tid=69525

      http://www.cnblogs.com/leon19870907/articles/1978065.html

18.   繪半透明矩形
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(ctx,[[UIColor blackColor] colorWithAlphaComponent:0.5].CGColor);
        CGContextAddRect(ctx, CGRectMake(0, 0, 320, 44));
        CGContextClosePath(ctx);
        CGContextDrawPath(ctx, kCGPathFill);

19.  GPUImage

       https://github.com/BradLarson/GPUImage

       先編譯framework目錄下GPUImage.xcodeproj,產生.a,再編譯examples下某個應用程式。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.