2016년 1월 12일 화요일

ImageView 이미지가 커서 나는 OutOfMemory를 방지하기 위해 축소하세요~




안드로이드개발 TIP



안드로이드에서 이클립스에서 자바로 개발할때 이미지가 커서나는 에러가 있는데, 여러요인중 이미지가 커서 나는 에러가 있어요
참고하세요~

ImageView 이미지가 커서 나는 OutOfMemory를 방지하기 위해 축소하세요~

샘플소스)
ImageView ivUnit = new ImageView(getContext());
LayoutParams lpImgUnit = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
ivUnit.setLayoutParams(lpImgUnit);
ivUnit.setImageBitmap(decodeSampledBitmapFromResource(getResources(), R.drawable.intro01_android, 140, 300));
((ViewPager)pager).addView(ivUnit, 0); //뷰를  추가


/*
   * 이미지가 커서 나는 outofmemory를 방지하기 위해 축소해준다
 */
decodeSampledBitmapFromResource(Resources res, int resId,
        int reqWidth, int reqHeight) {
    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInImgSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInImgSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    
     // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;
    if (height > reqHeight || width > reqWidth) {
        if (width > height) {
            inSampleSize = Math.round((float)height / (float)reqHeight);
        } else {
            inSampleSize = Math.round((float)width / (float)reqWidth);
        }
    }
    return inSampleSize;

}

즐거운 시간 보내세요~


댓글 없음:

댓글 쓰기