首页 > 代码库 > 缩放图片,并截取中间位置显示
缩放图片,并截取中间位置显示
代码:
- (void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view. UIImage *imagePicture=[UIImage imageNamed:@"1.jpg"]; UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(50, 100, 200, 200)]; imageView.image=[self scaleImage:imagePicture size:CGSizeMake(300, 200)]; imageView.backgroundColor=[UIColor redColor]; [self.view addSubview:imageView]; }//缩放图片,并截取中间位置显示-(UIImage*)scaleImage:(UIImage *)image size:(CGSize )size{ CGSize imgSize = image.size; //原图大小 CGSize viewSize = size; //视图大小 CGFloat imgwidth = 0; //缩放后的图片宽度 CGFloat imgheight = 0; //缩放后的图片高度 //视图横长方形及正方形 if (viewSize.width >= viewSize.height) { //缩小 if (imgSize.width > viewSize.width && imgSize.height > viewSize.height) { imgwidth = viewSize.width; imgheight = imgSize.height/(imgSize.width/imgwidth); } //放大 if(imgSize.width < viewSize.width){ imgwidth = viewSize.width; imgheight = (viewSize.width/imgSize.width)*imgSize.height; } //判断缩放后的高度是否小于视图高度 imgheight = imgheight < viewSize.height?viewSize.height:imgheight; } //视图竖长方形 if (viewSize.width < viewSize.height) { //缩小 if (imgSize.width > viewSize.width && imgSize.height > viewSize.height) { imgheight = viewSize.height; imgwidth = imgSize.width/(imgSize.height/imgheight); } //放大 if(imgSize.height < viewSize.height){ imgheight = viewSize.width; imgwidth = (viewSize.height/imgSize.height)*imgSize.width; } //判断缩放后的高度是否小于视图高度 imgwidth = imgwidth < viewSize.width?viewSize.width:imgwidth; } //重新绘制图片大小 UIImage *i; UIGraphicsBeginImageContext(CGSizeMake(imgwidth, imgheight)); [image drawInRect:CGRectMake(0, 0, imgwidth, imgheight)]; i=UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); //截取中间部分图片显示 if (imgwidth > 0) { CGImageRef newImageRef = CGImageCreateWithImageInRect(i.CGImage, CGRectMake((imgwidth-viewSize.width)/2, (imgheight-viewSize.height)/2, viewSize.width, viewSize.height)); return [UIImage imageWithCGImage:newImageRef]; }else{ CGImageRef newImageRef = CGImageCreateWithImageInRect(image.CGImage, CGRectMake((imgwidth-viewSize.width)/2, (imgheight-viewSize.height)/2, viewSize.width, viewSize.height)); return [UIImage imageWithCGImage:newImageRef]; }}
缩放图片,并截取中间位置显示
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。