android中一些bitmap的简单处理
[1].[代码] [Java]代码 跳至 [1]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | //根据指定的bitmap路径加载,并定义好了目标的大小 publicstatic Bitmap decodeFile(String path, intdstWidth, intdstHeight) { Options options = newOptions(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options); options.inJustDecodeBounds = false; options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, dstWidth, dstHeight); Bitmap unscaledBitmap = BitmapFactory.decodeFile(path, options); returnunscaledBitmap; } /** * 获得经过处理的bitmap */ publicstatic Bitmap createScaledBitmap(Bitmap unscaledBitmap, intdstWidth, intdstHeight) { Rect srcRect = calculateSrcRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight(), dstWidth, dstHeight); Rect dstRect = calculateDstRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight(), dstWidth, dstHeight); Bitmap scaledBitmap = Bitmap.createBitmap(dstRect.width(), dstRect.height(), Config.ARGB_8888); Canvas canvas = newCanvas(scaledBitmap); canvas.drawBitmap(unscaledBitmap, srcRect, dstRect, newPaint(Paint.FILTER_BITMAP_FLAG)); returnscaledBitmap; } /** * 计算Option的inSampleSize属性 */ publicstatic int calculateSampleSize(intsrcWidth, intsrcHeight, intdstWidth, intdstHeight) { finalfloat srcAspect = (float) srcWidth / (float) srcHeight; finalfloat dstAspect = (float) dstWidth / (float) dstHeight; if(srcAspect > dstAspect) { returnsrcWidth / dstWidth; }else{ returnsrcHeight / dstHeight; } } /** * 计算源文件的Rect */ publicstatic Rect calculateSrcRect(intsrcWidth, intsrcHeight, intdstWidth, intdstHeight) { returnnew Rect(0,0, srcWidth, srcHeight); } /** * 计算目标bitmap的rect区域 */ publicstatic Rect calculateDstRect(intsrcWidth, intsrcHeight, intdstWidth, intdstHeight) { finalfloat srcAspect = (float) srcWidth / (float) srcHeight; finalfloat dstAspect = (float) dstWidth / (float) dstHeight; if(srcAspect > dstAspect) { returnnew Rect(0,0, dstWidth, (int) (dstWidth / srcAspect)); }else{ returnnew Rect(0,0, (int) (dstHeight * srcAspect), dstHeight); } } /** * View转化为BitMap */ publicstatic Bitmap convertViewToBitmap(View view) { view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); view.layout(0,0, view.getMeasuredWidth(), view.getMeasuredHeight()); view.buildDrawingCache(); Bitmap bitmap = view.getDrawingCache(); returnbitmap; } |