ios实现下载图片的裁减和显示
使用如下的方法可以裁减的同时保证了不丢失像素。
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// Set appIcon and clear temporary data/image
UIImage *image = [[UIImage alloc] initWithData:self.activeDownload];
if (image.size.width != kAppIconSize || image.size.height != kAppIconSize)
{
//set the frame for the picture
CGSize itemSize = CGSizeMake(kAppIconSize, kAppIconSize);
//if the width is differ from height,than check
if (image.size.width < image.size.height) {
itemSize.width = (image.size.width/image.size.height)*kAppIconSize;
NSLog(@"the width cut is %f",itemSize.width);
}
// self.kids.appIcon = [self resizeToSize:itemSize withOrignalSize:image.size withImage:image thenCropWithRect:CGRectMake(0, 0, 70.0f, 70.0f)];
UIGraphicsBeginImageContextWithOptions(itemSize, NO, 0.0f);
CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
NSLog(@"the picture width is %f %f",image.size.width,image.size.height);
[image drawInRect:imageRect];
self.kids.appIcon = UIGraphicsGetImageFromCurrentImageContext();
NSLog(@"the picture end width is %f %f",self.kids.appIcon.size.width,self.kids.appIcon.size.height);
UIGraphicsEndImageContext();
}
else
{
self.kids.appIcon = image;
}
[image release];
self.activeDownload = nil;
// Release the connection now that it's finished
self.imageConnection = nil;
// call our delegate and tell it that our icon is ready for display
if (self.completionHandler)
self.completionHandler();
}
然后需要注意的是,使用uibutton要使用setimage而不是setbackgroundimage来加载图片。否则显示的图片总是70X70的kAppIconSize的大小当图片宽高比例明显不同时候就会出现拉伸。所以要注意。
然后使用setcontentmode来控制一下显示的内容才会有效。