我正在尝试缩小我用照片库中的图片来缩小我用来触摸移动的图像,就像我们用相机使用UIImagepicker setEditing to Yes方法(或者像相机应用程序)拍照一样。
我正在尝试使用以下方法传入一些基于touchesmoved的参数但是我没有得到预期的效果?我可能做错了什么?
-(UIImage*)scaleToSize:(UIImage *)img:(CGSize)size
{
// Create a bitmap graphics context
// This will also set it as the current context
UIGraphicsBeginImageContext(size);
// Draw the scaled image in the current context
[img drawInRect:CGRectMake(0, 0, size.width, size.height)];
// Create a new image from current context
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// Pop the current context from the stack
UIGraphicsEndImageContext();
// Return our new scaled image
return scaledImage;
}
-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UIImage *img = [self scaleToSize:imgView.image:CGSizeMake(touch1.x,touch1.y)];
imgView.image=img;
}
如果我以某种方式缩放它,我怎样才能保存缩放图像?
答案 0 :(得分:1)
在评论的基础上,图像会扭曲,因为它会将图像绘制到指定的矩形中,如果新尺寸与原始图像的宽高比(宽度/高度)不同,那么它将显得扭曲。 / p>
您需要一些逻辑来确保新的宽度和高度具有相同的宽高比,例如:
CGFloat newHeight = imageView.frame.size.height * size.width / imageView.frame.size.width;
如果你将图形上下文设置为size.width和newHeight,然后将图像绘制到这个矩形中,它将保持纵横比。
您可能希望在其中添加一些额外的逻辑,以根据给定宽度的高度或新高度创建新宽度,具体取决于哪个尺寸是最大变化。
希望这有帮助,
戴夫