Android:Example:DipCalc
Android의 dip와 pixel의 단위를 변환할 수 있는 클래스 샘플.
Source code
package ---;
/**
* 수학적 계산이 포함된 유틸리티 클래스.
*
* @author cwlee
* @since 2013-08-08
*/
public class Math {
/** 생성자를 지원하지 않는다. */
protected Math() {
throw new UnsupportedOperationException();
}
// -----------
// For screen.
// -----------
/** '중간'밀도화면의 dip 상수 (160). */
public static final int kMediumDensityConstant = 160;
/**
* DIP변환을 위한 기준(Standard)상수 (160).<br>
*
* <h2>Remarks.</h2> The density-independent pixel is equivalent to one
* physical pixel on a 160 dpi screen,<br>
* which is the baseline density assumed by the system for a "medium"
* density screen.
*/
public static final int kDipConvertConstant = kMediumDensityConstant;
// ------------------------
// Argument error constant.
// ------------------------
/** 화면밀도의 값이 0과 같거나 음수이다. */
public static final int kDisplayDensityArgumentError = -1;
/** Pixel값이 음수이다. */
public static final int kPixelArgumentError = -2;
/** Dip값이 음수이다. */
public static final int kDipArgumentError = -2;
/**
* dip를 pixel단위로 변환한다.
*
* <h1>Warning.</h1> 외부에서 메서드호출시 try ~ catch의 복잡함을 피하기 위하여<br>
* 반환값으로 예외상황을 처리하였다.
*
* @param display_density
* 화면 밀도(dpi).
* @param dip
* 변환할 dip값.
* @return 변환된 pixel값.
*/
public static int convertDipToPixel(float display_density, float dip) {
// if (display_density <= 0) {
// throw new
// IllegalArgumentException("Argument 'display_density' is <= 0.");
// }
if (display_density <= 0) {
return kDisplayDensityArgumentError;
}
if (dip < 0) {
return kDipArgumentError;
}
return (int) (dip * (display_density / (float) kDipConvertConstant));
}
/**
* pixel을 dp단위로 변환한다.
*
* <h1>Warning.</h1> 외부에서 메서드호출시 try ~ catch의 복잡함을 피하기 위하여<br>
* 반환값으로 예외상황을 처리하였다.
*
* @param display_density
* 화면 밀도(dpi).
* @param pixel
* 변환할 pixel값.
* @return 변환된 dip값. 만약, display_density가 0과 같거나 음수일 경우 -1을 반환하고,<br>
* pixel이 음수일 경우 -2를 반환한다.
*/
public static float convertPixelToDip(float display_density, int pixel) {
// if (display_density <= 0) {
// throw new
// IllegalArgumentException("Argument 'display_density' is <= 0.");
// }
if (display_density <= 0) {
return (float) kDisplayDensityArgumentError;
}
if (pixel < 0) {
return (float) kPixelArgumentError;
}
return (float) (((float) pixel) * kDipConvertConstant / display_density);
}
}