当前位置:操作系统 > 安卓/Android >>

分享一个Android图片转换类 1. Bitmap去色,转换为黑白的灰度图, 2. Bitmap图片加圆角效果

今天下午弄了半天实现了图片变黑白和圆角效果,发出来大家共享一下~
其中思路主要来自www.stackoverflow.com

不多说,直接贴代码,欢迎大家交流自己的方法~

 1/** *//**
 2 * 处理图片的工具类.
 3 *
 4 */
 5public class ImageTools {
 6   
 7    /** *//**
 8     * 图片去色,返回灰度图片
 9     * @param bmpOriginal 传入的图片
10     * @return 去色后的图片
11     */
12    public static Bitmap toGrayscale(Bitmap bmpOriginal) {
13        int width, height;
14        height = bmpOriginal.getHeight();
15        width = bmpOriginal.getWidth();   
16
17        Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
18        Canvas c = new Canvas(bmpGrayscale);
19        Paint paint = new Paint();
20        ColorMatrix cm = new ColorMatrix();
21        cm.setSaturation(0);
22        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
23        paint.setColorFilter(f);
24        c.drawBitmap(bmpOriginal, 0, 0, paint);
25        return bmpGrayscale;
26    }
27   
28   
29    /** *//**
30     * 去色同时加圆角
31     * @param bmpOriginal 原图
32     * @param pixels 圆角弧度
33     * @return 修改后的图片
34     */
35    public static Bitmap toGrayscale(Bitmap bmpOriginal, int pixels) {
36        return toRoundCorner(toGrayscale(bmpOriginal), pixels);
37    }
38   
39    /** *//**
40     * 把图片变成圆角
41     * @param bitmap 需要修改的图片
42     * @param pixels 圆角的弧度
43     * @return 圆角图片
44     */
45    public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
46
47        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
48                .getHeight(), Config.ARGB_8888);
49        Canvas canvas = new Canvas(output);
50
51        final int color = 0xff424242;
52        final Paint paint = new Paint();
53        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
54        final RectF rectF = new RectF(rect);
55        final float roundPx = pixels;
56
57        paint.setAntiAlias(true);
58        canvas.drawARGB(0, 0, 0, 0);
59        paint.setColor(color);
60        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
61
62        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
63        canvas.drawBitmap(bitmap, rect, rect, paint);
64
65        return output;
66    }
67
68   
69    /** *//**
70     * 使圆角功能支持BitampDrawable
71     * @param bitmapDrawable
72     * @param pixels
73     * @return
74     */
75    public static BitmapDrawable toRoundCorner(BitmapDrawable bitmapDrawable, int pixels) {
76        Bitmap bitmap = bitmapDrawable.getBitmap();
77        bitmapDrawable = new BitmapDrawable(toRoundCorner(bitmap, pixels));
78        return bitmapDrawable;
79    }
80}

补充:移动开发 , Android ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,