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;
        }
  • 相关阅读:
    js中的this指针(五)
    一个链式调用 setTimeout的例子
    js中的this指针(四)
    js中的this指针(三)
    NOJ 爱过
    Greatest Greatest Common Divisor HD5207
    Greatest Greatest Common Divisor HD5207
    Greatest Greatest Common Divisor HD5207
    Greatest Greatest Common Divisor HD5207
    Four Inages Strateg
  • 原文地址:https://www.cnblogs.com/a0000/p/3442557.html
Copyright © 2011-2022 走看看