Getting the visible rect of an UIScrollView's content

前端 未结 8 419
故里飘歌
故里飘歌 2020-11-30 19:17

How can I go about finding out the rect (CGRect) of the content of a displayed view that is actually visible on screen.

myScrollView.bounds

相关标签:
8条回答
  • 2020-11-30 19:47

    You have to compute it using UIScrollView's contentOffset and contentSize properties, like so:

    CGRect visibleRect;
    visibleRect.origin = scrollView.contentOffset;
    visibleRect.size = scrollView.contentSize;
    

    You can then log it for sanity-testing:

    NSLog( @"Visible rect: %@", NSStringFromCGRect(visibleRect) );
    

    To account for zooming (if this isn't already done by the contentSize property) you would need to divide each coordinate by the zoomScale, or for better performance you would multiply by 1.0 / zoomScale:

    CGFloat scale = (CGFloat) 1.0 / scrollView.zoomScale;
    if ( isless(scale, 1.0) )      // you need to #include <math.h> for isless()
    {
        visibleRect.origin.x *= scale;
        visibleRect.origin.y *= scale;
        visibleRect.size.width *= scale;
        visibleRect.size.height *= scale;
    }
    

    Aside: I use isless(), isgreater(), isequal() etc. from math.h because these will (presumably) do the right thing regarding 'unordered' floating-point comparison results and other weird & wonderful architecture-specific FP cases.


    Edit: You need to use bounds.size instead of contentSize when calculating visibleRect.size.

    0 讨论(0)
  • 2020-11-30 19:48

    Or you could simply do

    CGRect visibleRect = [scrollView convertRect:scrollView.bounds toView:zoomedSubview];
    

    Swift

    let visibleRect = scrollView.convert(scrollView.bounds, to: zoomedSubview)
    
    0 讨论(0)
提交回复
热议问题