我正在尝试将一个imgView集中在scrollView中,这样当我放大时,它将保持正确居中(就像照片应用程序一样)。
首次加载屏幕时,它会居中。当我捏合并开始变焦时,位置会自动调整,使图像不再居中。在捏/缩放照片之前和之后查看。 红色是滚动视图的背景颜色。
以下是我用于在滚动视图中创建imgView并将其置于中心的代码。 (MonoTouch,但应该转换为Obj-C easy)
private void LoadPageContent(int page) { // TODO:用于加载要在此面板/页面上显示的图像或代码的代码
//Each page will have it's own scrollview for scrolling and zooming that image on the page
var panelScrollView = new UIScrollView();
_panels.Add (panelScrollView);
panelScrollView.CanCancelContentTouches=false;
panelScrollView.ClipsToBounds = true;
panelScrollView.MinimumZoomScale = 1f;
panelScrollView.MaximumZoomScale = 50.0f;
panelScrollView.MultipleTouchEnabled = true;
panelScrollView.ScrollEnabled = true;
panelScrollView.UserInteractionEnabled=true;
var ui = new UIImage (_assetImages[page], 1.0f, UIImageOrientation.Up);
UIImageView imgView = new UIImageView(ui);
panelScrollView.Frame = new RectangleF(scrollView.Frame.Width * (_numberOfPanels - 1),
0,
_pageWidthPortrait,
scrollView.Frame.Height);
panelScrollView.BackgroundColor = UIColor.Red;
//scale down image to get proper fitted imgview dimensions
float nPercentW = (panelScrollView.Frame.Width / (float)imgView.Image.Size.Width);
float nPercentH = (panelScrollView.Frame.Height / (float)imgView.Image.Size.Height);
float newPercent;
if (nPercentH >= nPercentW)
{
//wider than it is tall
newPercent = nPercentW;
}
else{
//taller than it is wide..
newPercent = nPercentH;
}
int newWidth1 = Convert.ToInt32(imgView.Image.Size.Width * newPercent);
int newHeight = Convert.ToInt32(imgView.Image.Size.Height * newPercent);
panelScrollView.ViewForZoomingInScrollView += (UIScrollView sv) => {
return imgView;
};
imgView.Frame = new RectangleF(0,0,newWidth1, newHeight);
imgView.Center = new PointF(panelScrollView.Frame.Width /2,
(panelScrollView.Frame.Height/2));
//ScaleToFill and ScaleAspect fit - i used scaleaspectfit and it had the same problem
//I tried scaletofill but resizing the imgView to fit the proper view dimensions so it is like an aspect fit, but same problem
imgView.ContentMode=UIViewContentMode.ScaleToFill;//ScaleAspectFit;
imgView.UserInteractionEnabled=true;
panelScrollView.ContentSize = imgView.Image.Size;
panelScrollView.DidZoom += (object sender, EventArgs e) => {
};
panelScrollView.AddSubview(imgView);
scrollView.AddSubview(panelScrollView);
}
答案 0 :(得分:2)
这对我来说很好
- (void)centerScrollViewContents {
CGSize boundsSize = ScrollView.bounds.size;
CGRect contentsFrame = ImageView.frame;
if (contentsFrame.size.width < boundsSize.width) {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0f;
} else {
contentsFrame.origin.x = 0.0f;
}
if (contentsFrame.size.height < boundsSize.height) {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0f;
} else {
contentsFrame.origin.y = 0.0f;
}
ImageView.frame = contentsFrame;
}
您必须在
中调用此方法- (void)scrollViewDidZoom:(UIScrollView *)scrollView