差=

2016-06-23 52 views
0

UIImage的兩種方法將UIImageView差=

第一:

self.imageview.image = [UIImage imageNamed:@"clothing.png"]; 

二:

self.imageview.layer.contents = (__bridge id _Nullable)([[UIImage imageNamed:@"clothing.png"] CGImage]); 

兩種方式有什麼區別?

哪一個更好?

事實上,我想要做的是在UIImageView中顯示一個PNG的一部分。 有兩種方式:

第一:

UIImage *image = [UIImage imageNamed:@"clothing.png"]; 
CGImageRef imageRef = CGImageCreateWithImageInRect(image, rect); 
self.imageview.image = [UIImage imageWithCGImage:imageRef]; 

二:

self.imageview2.layer.contents = (__bridge id _Nullable)([[UIImage imageNamed:@"clothing.png"] CGImage]);//way2 
self.imageview2.layer.contentsRect = rect; 

哪一個更好?爲什麼?謝謝!

+0

第一個選項比第二個更好.. –

+0

如果'UIImage'的方向不是'UIImageOrientationUp',則可能會得到不同的結果。 – KudoCC

+0

你可以看到我的編輯。 – AnthoPak

回答

0

當然,更好的辦法是第一個:

self.imageview.image = [UIImage imageNamed:@"clothing.png"]; 

事實上,這是一個UIImageView爲構建方式。

爲了便於說明,每個視圖(UIView,UIImageView等)都有一個.layer屬性在其上添加可視內容。在這裏你正在添加一個圖像。您可以通過一個UIView獲得相同的結果。但是,在演出條款和清晰度方面,您應該(必須)使用.image屬性。

編輯:

即使你的新的編輯,第一選擇仍是最好的一個。

0

首先

self.imageview.image = [UIImage imageNamed:@"clothing.png"]; 

通過使用此您可以將圖像直接分配給任何的UIImageView雖然

self.imageview.layer.contents = (__bridge id _Nullable)([[UIImage imageNamed:@"clothing.png"] CGImage]); 

您不能直接分配圖像分層。所以你需要把一個CGImage放入一個圖層。

所以首先是永遠最好的。謝謝。

0

第一個選項是更好的,橋的概念引入ARC

0

之前用你能做到這一點,但它來修改圖像,讓您的責任image.CGImage得出正確尊重imageOrientationcontentMode等。如果您將圖片設置爲imageView.image = image;,蘋果有責任做到這一點。

我給你造成問題的例子: 爲image.CGImage不包含圖像的方向,因此,如果您直接設置它,如果源圖像不UIImageOrientationUp,圖像將被旋轉的,除非你「來解決方向「這樣的源圖像。 (你可以得到一個形象是不UIImageOrientationUp,只是採取的照片,你的iPhone)

- (UIImage *)fixOrientation { 
    if (self.imageOrientation == UIImageOrientationUp) return self; 

    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale); 
    [self drawInRect:(CGRect){0, 0, self.size}]; 
    UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    return normalizedImage; 
} 

這裏有兩個屏幕截圖,首先是直接設置image.CGImage到layer.contents,二是設置圖像到imageView.image。 enter image description here enter image description here

因此請務必使用imageView.image,除非你知道自己在做什麼。