Quiero establecer un UIImageView con UIImage
y poner esta imageview dentro de UIScrollView
para obtener un acercamiento de esta imagen; y quiero que UIImageView
y UIScrollView
entren en el rect en el centro de la vista ... ¿es posible?IOS: agregue imageview en scrollview para tener zoom
Respuesta
- Indica tu controlador de vista como un
<UIScrollViewDelegate>
- Dibuje su
UIScrollView
el tamaño que desee para el rectángulo en el centro de la vista. Establezca el zoom máximo en el inspector en algo más grande que 1. Como 4 o 10. - Haga clic derecho en la vista de desplazamiento y conecte el delegado a su controlador de vista.
- Dibuje su
UIImageView
en elUIScrollView
y configúrelo con la imagen que desee. Hazlo del mismo tamaño que elUIScrollView
. - Ctrl + resistencia de forma que
UIImageView
a la.h
de su controlador de Vista para crear unIBOutlet
para laUIImageView
, lo llama algo inteligente comoimageView
. añadir este código:
-(UIView *) viewForZoomingInScrollView:(UIScrollView *)scrollView { return self.imageView; }
Ejecutar la aplicación y pellizco y la bandeja hasta que el contenido de su corazón.
¿Puede hacer un ejemplo de esto pero programáticamente? – fawrkes
de lejos la solución más simple y clara que he encontrado – anthonypliu
@Justin Paulson ¿Podemos restringir el zoom al tamaño de la imagen. No quiero que el usuario se aleje del tamaño de la imagen. ¿Pueden ayudarme? –
Descargar this y this archivos. Los necesitarás para manejar toques.
Añadir a la vista del delegado ScrollView <UIScrollViewDelegate>
y declaran los puntos de venta:
@property (nonatomic, retain) IBOutlet UIScrollView *imageScrollView;
@property (nonatomic, retain) UIImageView *imageView;
Importe el archivo descargado dentro de la pantalla y hacer:
#import "TapDetectingImageView.h"
#define ZOOM_STEP 2.0
@interface myView (UtilityMethods)
- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center;
@end
@implementation myView
@synthesize imageScrollView, imageView;
- (void)viewDidLoad
{
[super viewDidLoad];
//Setting up the scrollView
imageScrollView.bouncesZoom = YES;
imageScrollView.delegate = self;
imageScrollView.clipsToBounds = YES;
//Setting up the imageView
imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"myImage.png"]];
imageView.userInteractionEnabled = YES;
imageView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin);
//Adding the imageView to the scrollView as subView
[imageScrollView addSubview:imageView];
imageScrollView.contentSize = CGSizeMake(imageView.bounds.size.width, imageView.bounds.size.height);
imageScrollView.decelerationRate = UIScrollViewDecelerationRateFast;
//UITapGestureRecognizer set up
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
UITapGestureRecognizer *twoFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTwoFingerTap:)];
[doubleTap setNumberOfTapsRequired:2];
[twoFingerTap setNumberOfTouchesRequired:2];
//Adding gesture recognizer
[imageView addGestureRecognizer:doubleTap];
[imageView addGestureRecognizer:twoFingerTap];
[singleTap release];
[doubleTap release];
[twoFingerTap release];
// calculate minimum scale to perfectly fit image width, and begin at that scale
float minimumScale = 1.0;//This is the minimum scale, set it to whatever you want. 1.0 = default
imageScrollView.maximumZoomScale = 4.0;
imageScrollView.minimumZoomScale = minimumScale;
imageScrollView.zoomScale = minimumScale;
[imageScrollView setContentMode:UIViewContentModeScaleAspectFit];
[imageView sizeToFit];
[imageScrollView setContentSize:CGSizeMake(imageView.frame.size.width, imageView.frame.size.height)];
}
- (void)scrollViewDidZoom:(UIScrollView *)aScrollView {
CGFloat offsetX = (imageScrollView.bounds.size.width > imageScrollView.contentSize.width)?
(imageScrollView.bounds.size.width - imageScrollView.contentSize.width) * 0.5 : 0.0;
CGFloat offsetY = (imageScrollView.bounds.size.height > imageScrollView.contentSize.height)?
(imageScrollView.bounds.size.height - imageScrollView.contentSize.height) * 0.5 : 0.0;
imageView.center = CGPointMake(imageScrollView.contentSize.width * 0.5 + offsetX,
imageScrollView.contentSize.height * 0.5 + offsetY);
}
- (void)viewDidUnload {
self.imageScrollView = nil;
self.imageView = nil;
}
#pragma mark UIScrollViewDelegate methods
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return imageView;
}
#pragma mark TapDetectingImageViewDelegate methods
- (void)handleDoubleTap:(UIGestureRecognizer *)gestureRecognizer {
// zoom in
float newScale = [imageScrollView zoomScale] * ZOOM_STEP;
if (newScale > self.imageScrollView.maximumZoomScale){
newScale = self.imageScrollView.minimumZoomScale;
CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecognizer locationInView:gestureRecognizer.view]];
[imageScrollView zoomToRect:zoomRect animated:YES];
}
else{
newScale = self.imageScrollView.maximumZoomScale;
CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecognizer locationInView:gestureRecognizer.view]];
[imageScrollView zoomToRect:zoomRect animated:YES];
}
}
- (void)handleTwoFingerTap:(UIGestureRecognizer *)gestureRecognizer {
// two-finger tap zooms out
float newScale = [imageScrollView zoomScale]/ZOOM_STEP;
CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecognizer locationInView:gestureRecognizer.view]];
[imageScrollView zoomToRect:zoomRect animated:YES];
}
#pragma mark Utility methods
- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center {
CGRect zoomRect;
// the zoom rect is in the content view's coordinates.
// At a zoom scale of 1.0, it would be the size of the imageScrollView's bounds.
// As the zoom scale decreases, so more content is visible, the size of the rect grows.
zoomRect.size.height = [imageScrollView frame].size.height/scale;
zoomRect.size.width = [imageScrollView frame].size.width/scale;
// choose an origin so as to get the right center.
zoomRect.origin.x = center.x - (zoomRect.size.width/2.0);
zoomRect.origin.y = center.y - (zoomRect.size.height/2.0);
return zoomRect;
}
hecho!
Básicamente lo que hace este código es agregar el imageView
como subvista del imageScrollView
.
Luego, agrega los métodos de clase TapDetecting
al scrollView, para reconocer el número de toques, el pellizco que hace el usuario y agregar funcionalidades de acercamiento.
Puede configurar el minimumScale
de la imagen, si se deja 1.0
la imagen debe mostrarse como-que-sea (si se establece un poco más bajo que está siendo ampliado), y la maximumZoomScale
, sugiero que se vaya a 4, está bien!
Ahora, puede cargar imágenes programáticamente desde allí.
Lo último que debe hacer es insertar un UIScrollView
dentro de su archivo xib y vincularlo al imageScrollView
. Tendrás la imagen en el centro perfecto, puedes tocarla dos veces para hacer zoom, pellizcar para hacer zoom mientras configuras en el código.
Esto es como una receta de cocina. Los pasos son correctos pero no explicas por qué debería hacerlo de esta manera. Esto lo ayudaría a él y a otros más al final. – Pfitz
Este es básicamente el código que estoy usando en mis aplicaciones. Voy a explicar – Phillip
No me malinterpreten, el código es bueno, pero el porqué también es importante. De lo contrario, no sabrá cómo resolver un problema similar. – Pfitz
He escrito una aplicación de ejemplo que también admite AutoLayout y Storyboards para demostrar este comportamiento.Espero que ahorre tiempo a todos tratando de resolver esto: http://rexstjohn.com/facebook-like-ios-photo-modal-gallery-swipe-gestures/.
Con Swift 4 y iOS 11, puede usar una de las dos soluciones siguientes para resolver su problema.
# 1. Utilizando inserciones
ViewController.swift
final class ViewController: UIViewController {
private let scrollView = ImageScrollView(image: UIImage(named: "image")!)
override func viewDidLoad() {
view.backgroundColor = .black
view.addSubview(scrollView)
scrollView.frame = view.frame
scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
}
ImageScrollView.swift
import UIKit
final class ImageScrollView: UIScrollView {
private let imageView = UIImageView()
override var frame: CGRect {
didSet {
if frame.size != oldValue.size { setZoomScale() }
}
}
required init(image: UIImage) {
super.init(frame: .zero)
imageView.image = image
imageView.sizeToFit()
addSubview(imageView)
contentSize = imageView.bounds.size
contentInsetAdjustmentBehavior = .never // Adjust content according to safe area if necessary
showsVerticalScrollIndicator = false
showsHorizontalScrollIndicator = false
alwaysBounceHorizontal = true
alwaysBounceVertical = true
delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Helper methods
func setZoomScale() {
let widthScale = frame.size.width/imageView.bounds.width
let heightScale = frame.size.height/imageView.bounds.height
let minScale = min(widthScale, heightScale)
minimumZoomScale = minScale
zoomScale = minScale
}
}
extension ImageScrollView: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
let imageViewSize = imageView.frame.size
let scrollViewSize = scrollView.bounds.size
let verticalInset = imageViewSize.height < scrollViewSize.height ? (scrollViewSize.height - imageViewSize.height)/2 : 0
let horizontalInset = imageViewSize.width < scrollViewSize.width ? (scrollViewSize.width - imageViewSize.width)/2 : 0
scrollView.contentInset = UIEdgeInsets(top: verticalInset, left: horizontalInset, bottom: verticalInset, right: horizontalInset)
}
}
# 2. Diseño automático utilizando
ViewController.swift
import UIKit
final class ViewController: UIViewController {
private let scrollView = ImageScrollView(image: UIImage(named: "image")!)
override func viewDidLoad() {
view.backgroundColor = .black
view.addSubview(scrollView)
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
override func viewDidLayoutSubviews() {
scrollView.setZoomScale()
}
}
ImageScrollView.swift
import UIKit
final class ImageScrollView: UIScrollView {
private let imageView = UIImageView()
private var imageViewBottomConstraint = NSLayoutConstraint()
private var imageViewLeadingConstraint = NSLayoutConstraint()
private var imageViewTopConstraint = NSLayoutConstraint()
private var imageViewTrailingConstraint = NSLayoutConstraint()
required init(image: UIImage) {
super.init(frame: .zero)
imageView.image = image
imageView.sizeToFit()
addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageViewLeadingConstraint = imageView.leadingAnchor.constraint(equalTo: leadingAnchor)
imageViewTrailingConstraint = imageView.trailingAnchor.constraint(equalTo: trailingAnchor)
imageViewTopConstraint = imageView.topAnchor.constraint(equalTo: topAnchor)
imageViewBottomConstraint = imageView.bottomAnchor.constraint(equalTo: bottomAnchor)
NSLayoutConstraint.activate([imageViewLeadingConstraint, imageViewTrailingConstraint, imageViewTopConstraint, imageViewBottomConstraint])
contentInsetAdjustmentBehavior = .never // Adjust content according to safe area if necessary
showsVerticalScrollIndicator = false
showsHorizontalScrollIndicator = false
alwaysBounceHorizontal = true
alwaysBounceVertical = true
delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Helper methods
func setZoomScale() {
let widthScale = frame.size.width/imageView.bounds.width
let heightScale = frame.size.height/imageView.bounds.height
let minScale = min(widthScale, heightScale)
minimumZoomScale = minScale
zoomScale = minScale
}
}
extension ImageScrollView: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
let yOffset = max(0, (bounds.size.height - imageView.frame.height)/2)
imageViewTopConstraint.constant = yOffset
imageViewBottomConstraint.constant = yOffset
let xOffset = max(0, (bounds.size.width - imageView.frame.width)/2)
imageViewLeadingConstraint.constant = xOffset
imageViewTrailingConstraint.constant = xOffset
layoutIfNeeded()
}
}
Fuentes:
- 1. Insertar ImageView en ScrollView con diseño automático en iOS 6
- 2. recortar una imagen ampliada en ImageView dentro de scrollView
- 3. Cómo hacer zoom ImageView en Android
- 4. ViewPager Android con ImageView con zoom
- 5. Abrir ImageView con Zoom y Desplazar
- 6. Márgenes redundantes al agregar ImageView a ScrollView en Android
- 7. Toque dos veces para acercar y pellizcar para hacer zoom en ImageView en android
- 8. ImageView Pinch-zoom Límites de escala y límites de panorámica
- 9. para imageview en Android
- 10. iOS MKMapVer zoom para mostrar todos los marcadores
- 11. Establecer zoom 100% predeterminado para iOS Safari sitio de representación
- 12. iOS: Agregue múltiples UIImageViews programáticamente en tiempo de ejecución
- 13. Uso de ImageView para vista panorámica
- 14. Establecer zoom para Webview
- 15. Desactivar zoom de doble toque en MKMapView (iOS 6)
- 16. Comportamiento indiferente del nivel de zoom en IOS 6 mapview
- 17. Android, ImageView sobre ImageView
- 18. Ver dentro de ScrollView no ocupa todo
- 19. Zoom en UIScrollView no funciona
- 20. ¿Algún truco para tener múltiples certificados de desarrollo de iOS?
- 21. Zoom específico en Google Maps
- 22. Imageview y PagerAdapter
- 23. ¿Cómo poner una imageview encima de otro imageview en Android
- 24. Android: ScrollView en LinearLayout vertical
- 25. Restablecer desplazamiento en ScrollView
- 26. Redacción de texto de iOS después de hacer zoom
- 27. Agregue Cocos2D para proyectar en xCode 4
- 28. iOS 5 MapKit se cuelga con superposiciones cuando zoom/pan
- 29. ¿Cómo configura setLayoutParams() para un ImageView?
- 30. ¿Cómo hacer que mi ImageView pueda ampliarse?
Así que desea que la imagen para hacer un zoom con un pellizco, pero todo lo demás en la vista de desplazamiento para suspender el mismo? – woz
sí ............. – CrazyDev
Sí, definitivamente es posible. ¿Has probado algo en absoluto? La mayoría de lo que está describiendo se puede hacer en el constructor de interfaz/guión gráfico –