Home | History | Annotate | Download | only in utils
      1 /*
      2  * Copyright (C) 2014 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package android.hardware.camera2.utils;
     18 
     19 import android.util.Size;
     20 
     21 import java.util.Collections;
     22 import java.util.Comparator;
     23 import java.util.List;
     24 
     25 import static com.android.internal.util.Preconditions.*;
     26 
     27 /**
     28  * Comparator for {@link Size} objects by the area.
     29  *
     30  * <p>This comparator totally orders by rectangle area. Tie-breaks on width.</p>
     31  */
     32 public class SizeAreaComparator implements Comparator<Size> {
     33     /**
     34      * {@inheritDoc}
     35      */
     36     @Override
     37     public int compare(Size size, Size size2) {
     38         checkNotNull(size, "size must not be null");
     39         checkNotNull(size2, "size2 must not be null");
     40 
     41         if (size.equals(size2)) {
     42             return 0;
     43         }
     44 
     45         long width = size.getWidth();
     46         long width2 = size2.getWidth();
     47         long area = width * size.getHeight();
     48         long area2 = width2 * size2.getHeight();
     49 
     50         if (area == area2) {
     51             return (width > width2) ? 1 : -1;
     52         }
     53 
     54         return (area > area2) ? 1 : -1;
     55     }
     56 
     57     /**
     58      * Get the largest {@code Size} from the list by comparing each size's area
     59      * by each other using {@link SizeAreaComparator}.
     60      *
     61      * @param sizes a non-{@code null} list of non-{@code null} sizes
     62      * @return a non-{@code null} size
     63      *
     64      * @throws NullPointerException if {@code sizes} or any elements in it were {@code null}
     65      */
     66     public static Size findLargestByArea(List<Size> sizes) {
     67         checkNotNull(sizes, "sizes must not be null");
     68 
     69         return Collections.max(sizes, new SizeAreaComparator());
     70     }
     71 }