使用UIPinchGestureRecognizer调整大小的UIImageView

时间:2012-11-07 19:43:48

标签: objective-c ios uiimageview uigesturerecognizer

我正在尝试使用UIPinchGestureRecognizer调整UIImageView的大小。应用简单的CGAffineTransform有效,但它会根据左上角调整大小,而我想根据图像的中心调整大小。我可以使用以下代码

获得所需的结果
-(IBAction)handlePinch:(UIPinchGestureRecognizer *)recognizer
{
UIImageView *view = [recognizer view];
float scale = recognizer.scale;
view.bounds = CGRectMake(0,  0, view.bounds.size.height*scale, view.bounds.size.width*scale);
recognizer.scale = 1;
}

问题在于,当我使用此代码时,图像会在调整大小时出现所有毛刺和波动。知道为什么会这样吗?

1 个答案:

答案 0 :(得分:0)

你可能正在以艰难的方式做到这一点。建议您考虑将UIImageView添加到UIScrollView,并让滚动视图为您完成工作。 E.g:

UIScrollViewDelegate标题:

#import <UIKit/UIKit.h>

@interface MyScrollViewController : UIViewController <UIScrollViewDelegate>

@end

显示设置允许缩放的滚动视图的实现:

#import "MyScrollViewController.h"

#define MIN_ZOOM_FACTOR 1
#define MAX_ZOOM_FACTOR 5

@interface MyScrollViewController () {
    UIScrollView *scrollView;
    UIImageView *imageView;
}

@end

@implementation MyScrollViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
    scrollView.backgroundColor = [UIColor clearColor];
    scrollView.delegate = self;
    scrollView.contentSize = CGSizeMake(self.view.bounds.size.width * MAX_ZOOM_FACTOR,
                                    self.view.bounds.size.height * MAX_ZOOM_FACTOR);
    scrollView.minimumZoomScale = MIN_ZOOM_FACTOR;
    scrollView.maximumZoomScale = MAX_ZOOM_FACTOR;

    imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"your_image_name.png"]];
    imageView.frame = scrollView.frame;
    imageView.contentMode = UIViewContentModeScaleAspectFit;

    [scrollView addSubview:imageView];
}

#pragma mark - Scroll view delegate methods

-(UIView *) viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return imageView;
}

@end

如果您想知道何时进行平移和缩放,缩放比例是什么等,请实现其他UIScrollViewDelegate方法。例如:

-(void)scrollViewDidZoom:(UIScrollView *)zoomedScrollingView{
    float zoomScale = scrollView.zoomScale;
    // Do something with zoomScale...
}