圆角处理图片

2018-08-28  本文已影响9人  小慕汐
public class DrawableUtils {
    
    /**
    * 将图片的四角圆弧化
    *
    * @param bitmap      原图
    * @param roundPixels 弧度
    * @return
    */
    public static Bitmap getRoundCornerImage(Bitmap bitmap, int roundPixels, int roundType) {
       int    width           = bitmap.getWidth();
       int    height          = bitmap.getHeight();
       Path   path            = checkRect(width, height, roundPixels, roundType);
       Bitmap roundRoundImage = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
       Canvas canvas          = new Canvas(roundRoundImage);
       Paint  paint           = new Paint();
       paint.setAntiAlias(true);// 抗锯齿
       paint.setFilterBitmap(true);// 抗锯齿
       
       paint.setColor(0xFF000000);
       canvas.drawPath(path, paint);
       paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));//设置相交模式
       
       canvas.drawBitmap(bitmap, 0, 0, paint);
       return roundRoundImage;
    }
    
    public static Path checkRect(int width, int height, int roundPixels, int roundType) {
       Path  path = new Path();
       RectF rect = new RectF(0, 0, width, height);
       path.addRoundRect(rect, roundPixels, roundPixels, Path.Direction.CCW);
       if ((roundType & ROUND_LEFT_TOP) == 0) {
          path.addRect(0, 0, roundPixels, roundPixels, Path.Direction.CCW);
       }
       if ((roundType & ROUND_RIGHT_TOP) == 0) {
          path.addRect(width - roundPixels, 0, width, roundPixels, Path.Direction.CCW);
       }
       if ((roundType & ROUND_LEFT_BOTTOM) == 0) {
          path.addRect(0, height - roundPixels, roundPixels, height, Path.Direction.CCW);
       }
       if ((roundType & ROUND_RIGHT_BOTTOM) == 0) {
          path.addRect(width - roundPixels, height - roundPixels, width, height, Path.Direction.CCW);
       }
       return path;
    }
    
    public static final int ROUND_LEFT_TOP     = 8;
    public static final int ROUND_RIGHT_TOP    = 4;
    public static final int ROUND_LEFT_BOTTOM  = 2;
    public static final int ROUND_RIGHT_BOTTOM = 1;
}

用int的低位来表示各种状态:

  1. 1000 -> 8 - > 左上圆
  2. 0100 -> 6 - > 右上圆
  3. 0010 -> 4 - > 左下圆
  4. 0001 -> 1 - > 右下圆

1.创建一个path,然后add一个圆角,
2.通过是否有圆角来决定要不要覆盖圆角的位置
3.通过canvas.drawPath圆路径

原始图
右下圆角
左下圆角
下圆角
右上圆角
右圆角
左下右上圆角
左下右圆角
左上圆角
左上右下圆角
左圆角
右下左圆角
上圆角
左上右圆角
右上左圆角
全圆角
上一篇下一篇

猜你喜欢

热点阅读