我有一个UIImageView目标是按比例缩小它通过给它一个高度或宽度。
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg"]]];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
//Add image view
[self.view addSubview:imageView];
//set contentMode to scale aspect to fit
imageView.contentMode = UIViewContentModeScaleAspectFit;
//change width of frame
CGRect frame = imageView.frame;
frame.size.width = 100;
imageView.frame = frame;
图像确实调整了大小,但位置不在左上方。缩放image/imageView的最佳方法是什么?我如何纠正位置?
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg"]]];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
//set contentMode to scale aspect to fit
imageView.contentMode = UIViewContentModeScaleAspectFit;
//change width of frame
//CGRect frame = imageView.frame;
//frame.size.width = 100;
//imageView.frame = frame;
//original lines that deal with frame commented out, yo.
imageView.frame = CGRectMake(10, 20, 60, 60);
...
//Add image view
[myView addSubview:imageView];
上面的原始代码在iOS 4.2中运行得很好。
我发现创建一个CGRect并指定所有的顶部,左侧,宽度和高度值是在我的情况下调整位置的最简单的方法,这是在表格单元格中使用UIImageView。(仍然需要添加代码来释放对象)
通常我在我的应用程序中使用这种方法(Swift 2。x兼容的):
// Resize UIImage
func resizeImage(image:UIImage, scaleX:CGFloat,scaleY:CGFloat) ->UIImage {
let size = CGSizeApplyAffineTransform(image.size, CGAffineTransformMakeScale(scaleX, scaleY))
let hasAlpha = true
let scale: CGFloat = 0.0 // Automatically use scale factor of main screen
UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)
image.drawInRect(CGRect(origin: CGPointZero, size: size))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}