标签:style blog io color sp on div log bs
代码:
- (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]; } }
标签:style blog io color sp on div log bs
原文地址:http://www.cnblogs.com/yang-guang-girl/p/4135073.html