iOS将长方形的图片截成正方形显示

+(UIImage*)getSubImage:(UIImage *)image mCGRect:(CGRect)mCGRect centerBool:(BOOL)centerBool{
/*如若centerBool为Yes则是由中心点取mCGRect范围的图片*/
float imgWidth = image.size.width;
float imgHeight = image.size.height;
float viewWidth = mCGRect.size.width;
float viewHidth = mCGRect.size.height;
CGRect rect;
if(centerBool)
rect = CGRectMake((imgWidth-viewWidth)/2, (imgHeight-viewHidth)/2, viewWidth, viewHidth);
else{
if (viewHidth < viewWidth) {
if (imgWidth <= imgheight) {
rect = CGRectMake(0, 0, imgwidth, imgwidth*viewheight/viewwidth);
}else {
float width = viewwidth*imgheight/viewheight;
float x = (imgwidth - width)/2 ;
if (x > 0) {
rect = CGRectMake(x, 0, width, imgheight);
}else {
rect = CGRectMake(0, 0, imgwidth, imgwidth*viewheight/viewwidth);
}
}
}else {
if (imgwidth <= imgheight) {
float height = viewheight*imgwidth/viewwidth;
if (height < imgheight) {
rect = CGRectMake(0, 0, imgwidth, height);
}else {
rect = CGRectMake(0, 0, viewwidth*imgheight/viewheight, imgheight);
}
}else {
float width = viewwidth*imgheight/viewheight;
if (width < imgwidth) {
float x = (imgwidth - width)/2 ;
rect = CGRectMake(x, 0, width, imgheight);
}else {
rect = CGRectMake(0, 0, imgwidth, imgheight);
}
}
}
}

CGImageRef subImageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
CGRect smallBounds = CGRectMake(0, 0, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));

UIGraphicsBeginImageContext(smallBounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawImage(context, smallBounds, subImageRef);
UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];
UIGraphicsEndImageContext();

return smallImage;
}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。