[英]scaling an image for a cell
我正在尝试将图像添加到单元格中,但是可以正常使用,但是缩放比例并没有真正起作用,图像被缩放到一定的大小,并保持该大小,我输入到scale函数中的数字不会改变任何事情。自动缩放到某个恒定大小)
NSURL *url = [NSURL URLWithString:icon];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *logo=[UIImage imageWithData:data scale:4];
cell.imageView.layer.masksToBounds = YES;
cell.imageView.layer.cornerRadius = 10.0;
cell.imageView.image=logo;
实现此方法并使用它:
/*! Returns a UIImage which is resized image of the image provided.
@param image
The image to be resized.
@param size
The size of the image to be resized.
*/
+ (UIImage*)resizeImage:(UIImage *)image imageSize:(CGSize)size {
CGFloat imageWidth = image.size.width;
CGFloat imageHeight = image.size.height;
CGFloat requiredWidth = (imageWidth * size.height) / imageHeight;
UIGraphicsBeginImageContextWithOptions(CGSizeMake(requiredWidth, size.height), NO, [UIScreen mainScreen].scale);
[image drawInRect:CGRectMake(0, 0, requiredWidth, size.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
//here is the scaled image which has been changed to the size specified
UIGraphicsEndImageContext();
return newImage;
}
只需在如下声明的自定义单元类方法中编写掩蔽函数即可。
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
[self.imageView.layer setCornerRadius:10.0];
self.imageView.layer.masksToBounds = YES;
}
使用此功能可以根据需要缩放图像。
- (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
//UIGraphicsBeginImageContext(newSize);
float theScaleFactor = 0.0f;
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
if ([[UIScreen mainScreen] scale] == 2.0) {
theScaleFactor = 2.0f;
} else {
theScaleFactor = 0.0f;
}
} else {
theScaleFactor = 0.0f;
}
UIGraphicsBeginImageContextWithOptions(newSize, NO, theScaleFactor);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
希望这会帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.