mobile/android/base/gfx/IntSize.java

branch
TOR_BUG_9701
changeset 15
b8a032363ba2
equal deleted inserted replaced
-1:000000000000 0:e47b3a2209fe
1 /* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
2 * This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5
6 package org.mozilla.gecko.gfx;
7
8 import org.json.JSONException;
9 import org.json.JSONObject;
10
11 import android.util.FloatMath;
12
13 public class IntSize {
14 public final int width, height;
15
16 public IntSize(IntSize size) { width = size.width; height = size.height; }
17 public IntSize(int inWidth, int inHeight) { width = inWidth; height = inHeight; }
18
19 public IntSize(FloatSize size) {
20 width = Math.round(size.width);
21 height = Math.round(size.height);
22 }
23
24 public IntSize(JSONObject json) {
25 try {
26 width = json.getInt("width");
27 height = json.getInt("height");
28 } catch (JSONException e) {
29 throw new RuntimeException(e);
30 }
31 }
32
33 public int getArea() {
34 return width * height;
35 }
36
37 public boolean equals(IntSize size) {
38 return ((size.width == width) && (size.height == height));
39 }
40
41 public boolean isPositive() {
42 return (width > 0 && height > 0);
43 }
44
45 @Override
46 public String toString() { return "(" + width + "," + height + ")"; }
47
48 public IntSize scale(float factor) {
49 return new IntSize(Math.round(width * factor),
50 Math.round(height * factor));
51 }
52
53 /* Returns the power of two that is greater than or equal to value */
54 public static int nextPowerOfTwo(int value) {
55 // code taken from http://acius2.blogspot.com/2007/11/calculating-next-power-of-2.html
56 if (0 == value--) {
57 return 1;
58 }
59 value = (value >> 1) | value;
60 value = (value >> 2) | value;
61 value = (value >> 4) | value;
62 value = (value >> 8) | value;
63 value = (value >> 16) | value;
64 return value + 1;
65 }
66
67 public IntSize nextPowerOfTwo() {
68 return new IntSize(nextPowerOfTwo(width), nextPowerOfTwo(height));
69 }
70
71 public static boolean isPowerOfTwo(int value) {
72 if (value == 0)
73 return false;
74 return (value & (value - 1)) == 0;
75 }
76
77 public static int largestPowerOfTwoLessThan(float value) {
78 int val = (int)FloatMath.floor(value);
79 if (val <= 0) {
80 throw new IllegalArgumentException("Error: value must be > 0");
81 }
82 // keep dropping the least-significant set bits until only one is left
83 int bestVal = val;
84 while (val != 0) {
85 bestVal = val;
86 val &= (val - 1);
87 }
88 return bestVal;
89 }
90 }
91

mercurial