How do I tell when an image is clipped?

2019-08-12 07:13发布

问题:

If I have a LinearLayout containing ImageViews, how could I write code to tell which, if any, is clipped by the edge of the screen?

<LinearLayout android:id="@+id/imagecontainer"
              android:orientation="horizontal"
              android:layoutHeight="wrap_content"
              android:layoutWidth="fill_parent">

    <ImageView android:id="@+id/image1" .../>
    <ImageView android:id="@+id/image2" .../>

     ...

    <ImageView android:id="@+id/imageN" .../>

</LinearLayout>

I imagine something like, which would return an index or 0 if nobody is clipped. The semantics of the function call aren't really important... I just need some way to tell if there is clipping and if so, who is it?

int whichImageIsClipped(LinearLayout root) { ... }

回答1:

This may be a stretch, but you could try getGlobalVisibleRect(android.graphics.Rect, android.graphics.Point) on each of your children. If it returns false, you know it's completely out of view. If it returns true, you will need to compare the returned Rect with the expected size of your image.

Does that work for what you need?

Here is the code, in case anyone needs it:

public static Boolean isViewClipped(View view) {
  Rect rect = new Rect();
  Boolean completelyObscured = !view.getGlobalVisibleRect(rect);
  return completelyObscured || rect.width() < view.getWidth();
}