UIImageView控件在app中的使用频率想我也不用多说。离不了!在展示图片时,往往需要展示网络的图片!
图片缩放的背景
有时候,从互联网下载到的图片需要放在UIImageView中。但是我们app中需要的图片尺寸和比例不一定跟下载到的图片的尺寸和比例正好相等。这样的话,需要对网络的图片进行切割,来满足我们app中UIImageView控件的尺寸和比例。
图片切割代码
老规矩,上代码!
切割方法:
-(UIImage*)captureView:(UIView *)theView frame:(CGRect)fra{
UIGraphicsBeginImageContext(theView.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[theView.layer renderInContext:context];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRef ref = CGImageCreateWithImageInRect(img.CGImage, fra);
UIImage *i = [UIImage imageWithCGImage:ref];
CGImageRelease(ref);
return i;
}
使用例子:
// 请求成功
NSData *imgData=[request responseData];// 网络下载到的图片数据
UIImage * image = [UIImage imageWithData:imgData];
if (theId==[[_dictData objectForKey:@"channel_id"] intValue]) {
UIImageView *tmpImgView=[[[UIImageView alloc] initWithImage:image]autorelease];
UIImage *theImage= [self captureView:tmpImgView frame:CGRectMake(0, 30, 640, 360)];// 切割尺寸
CATransition *animation = [CATransition animation];
[animation setDuration:2.0];
[animation setFillMode:kCAFillModeForwards];
[animation setTimingFunction:[CAMediaTimingFunctionfunctionWithName:kCAMediaTimingFunctionEaseOut]];
[animation setType:@"rippleEffect"];// rippleEffect
[animation setSubtype:kCAAlignmentCenter];
[_imgPic.layer addAnimation:animation forKey:nil];
[_imgPic setImage:theImage];
}
说明:
其实,贴了这么多,关键的代码就是captureView方法和标红的3行代码。
之所以,贴这么多,因为,我们下载下来新图片,在变换的时候,需要为图片进行一些动画,这样看起了的图片切换不至于太单调!
mark一下了!
希望对你有所帮助!