zoukankan      html  css  js  c++  java
  • Android 截取圆形图片核心代码

    原文地址:http://www.eoeandroid.com/forum.php?mod=viewthread&tid=103093

    核心代码:

            Bitmap sourceBitmap = BitmapFactory.decodeResource(getResources(),
                    R.drawable.xiaohuai);
            //此处要求图片宽值<长度值
            int targetWidth = sourceBitmap.getWidth();
            int targetHeight = targetWidth;
            Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight,
                    Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(targetBitmap);
            //抗锯齿
            canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG
                    | Paint.FILTER_BITMAP_FLAG));
            Path path = new Path();
            path.addCircle(((float) targetWidth - 1) / 2,
                    ((float) targetHeight - 1) / 2,
                    (Math.min(((float) targetWidth), ((float) targetHeight)) / 2),
                    Path.Direction.CCW);
            canvas.clipPath(path);
    
            canvas.drawBitmap(sourceBitmap, new Rect(0, 0, sourceBitmap.getWidth(),
                    sourceBitmap.getHeight()), new Rect(0, 0, targetWidth,
                    targetHeight), null);
            ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
            imageView.setImageBitmap(targetBitmap);

    下面的代码更好,感谢同事的贡献

    注:保存Bitmap时须保存成PNG格式的,JPG不支持透明

    /**
         * 将圆形图片,返回Bitmap
         * @param bitmap 源Bitmap
         * @return
         */
        public static Bitmap getCircleBitmap(Bitmap bitmap) {
            int x = bitmap.getWidth();
            int y = bitmap.getHeight();
            Bitmap output = Bitmap.createBitmap(x,
                    y, Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
     
            final int color = 0xff424242;
            final Paint paint = new Paint();
            // 根据原来图片大小画一个矩形
            final Rect rect = new Rect(0, 0, x, y);
            paint.setAntiAlias(true);
            paint.setColor(color);
            // 画出一个圆
            canvas.drawCircle(x/2, x/2, x/2-5, paint);
            //canvas.translate(-25, -6);
            // 取两层绘制交集,显示上层
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            
            // 将图片画上去
            canvas.drawBitmap(bitmap, rect, rect, paint);
            // 返回Bitmap对象
            return output;
        }
  • 相关阅读:
    Linux下JDK安装位置
    Oracle中的User与Schema
    MFC中不同窗口间的切换
    MFC 动态的画线 画当前的线是清除上一次画的线
    VC ADO连接ACCESS步骤及错误处理
    虚继承和虚函数继承
    虚拟机无法连接连接U盘
    未能找到类型或命名空间
    VS2008 重构 封装字段 出错 无法使用
    vs2010 Visual Studio 遇到了异常。这可能是由某个扩展导致的
  • 原文地址:https://www.cnblogs.com/a0000/p/3442557.html
Copyright © 2011-2022 走看看