如何缩小图像并将其保持在Scrollview的中心

时间:2010-09-01 09:26:12

标签: iphone

在我的应用程序中,我需要使用cam捕获图像,然后将其传递给imageView,后者用作ScrollView的子视图。

要求是“图像必须便于缩小1/4尺寸,放大3倍”。

现在的问题是,当我缩小此图像时,图像会缩小,但它不会保持在中心的位置。它将其位置分别对应于手指的触摸。 (没有双击缩放,也不需要)

以下是代码..,

- (void)viewDidLoad 

{     [super viewDidLoad];

UIImage* tmpImage = nil;
tmpImage = [roomImage resizedImage:imageScrollView.frame.size interpolationQuality:0];
imageView = [[UIImageView alloc] initWithImage:tmpImage];
imageView.contentMode = UIViewContentModeScaleAspectFit;

imageScrollView.delegate = self;
imageScrollView.canCancelContentTouches = NO;
imageScrollView.minimumZoomScale = 0.25;
imageScrollView.maximumZoomScale = 3.00;


imageScrollView.clipsToBounds = YES;

[imageView sizeToFit];
[imageScrollView addSubview:imageView];

imageScrollView.contentSize = imageView.frame.size;
    imageScrollView.contentMode = UIViewContentModeScaleAspectFit;  
    imageScrollView.contentOffset = CGPointMake(imageScrollView.frame.size.width/2, imageScrollView.frame.size.height/2);
imageScrollView.autoresizesSubviews = YES;
imageScrollView.autoresizingMask =  UIViewAutoresizingFlexibleHeight |        UIViewAutoresizingFlexibleWidth   |  
UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | 
UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;


CGFloat f,x,y;

if(tmpImage.size.height > tmpImage.size.width)
{
    f = (imageScrollView.frame.size.height/tmpImage.size.height);
}
else
{
    f = (imageScrollView.frame.size.width/tmpImage.size.width);
}

x = (imageScrollView.frame.size.width - tmpImage.size.width*f)/2;
y = (imageScrollView.frame.size.height - tmpImage.size.height*f)/2;

imageView.bounds = CGRectMake(x, y,tmpImage.size.width, tmpImage.size.height);
[imageView setNeedsDisplay];
[imageScrollView setZoomScale:f animated:YES];
[imageScrollView setNeedsDisplay];

jpgPath = nil;
[roomImage release];
roomImage = nil;

}

希望任何人都可以帮助我..,

提前致谢..,

1 个答案:

答案 0 :(得分:0)

如果我正确理解你,你可以继承UIScrollView,并在layoutSubviews方法中使用以下内容来保持其内容集中:

-(void)layoutSubviews {

[super layoutSubviews];

CGSize boundsSize = self.bounds.size;
CGRect contentViewFrame  = contentView.frame;

if (contentViewFrame.size.width < boundsSize.width) {

    contentViewFrame.origin.x = (boundsSize.width - contentViewFrame.size.width) / 2;

} else {

    contentViewFrame.origin.x = 0;

}

if (contentViewFrame.size.height < boundsSize.height) {

    contentViewFrame.origin.y = (boundsSize.height - contentViewFrame.size.height) / 2;

} else {

    contentViewFrame.origin.y = 0;

}

contentView.frame = contentViewFrame;

}

contentView变量是一个iVar,在你的情况下代表你想要在scrollView中的imageView。希望这会有所帮助: - )