当前位置: 移动技术网 > IT编程>移动开发>Android > Android中使用Bitmap类将矩形图片转为圆形的方法

Android中使用Bitmap类将矩形图片转为圆形的方法

2019年07月24日  | 移动技术网IT编程  | 我要评论

qq发布中心头像,叶会长的温情面纱,zq锻炼教程下载

一般要做正圆形图片,只能是正方形的基础上才能实现,否则就变成椭圆了,下面说说如何使长方形的图片生成正圆形图片
废话不多说,没图没真相,先上图吧:
原图:

2016319163739626.jpg (480×800)

变成正圆后:

2016319163810889.jpg (480×800)

下面上代码:

public static bitmap makeroundcorner(bitmap bitmap) 
{ 
  int width = bitmap.getwidth(); 
  int height = bitmap.getheight(); 
  int left = 0, top = 0, right = width, bottom = height; 
  float roundpx = height/2; 
  if (width > height) { 
    left = (width - height)/2; 
    top = 0; 
    right = left + height; 
    bottom = height; 
  } else if (height > width) { 
    left = 0; 
    top = (height - width)/2; 
    right = width; 
    bottom = top + width; 
    roundpx = width/2; 
  } 
  zlog.i(tag, "ps:"+ left +", "+ top +", "+ right +", "+ bottom); 
 
  bitmap output = bitmap.createbitmap(width, height, bitmap.config.argb_8888); 
  canvas canvas = new canvas(output); 
  int color = 0xff424242; 
  paint paint = new paint(); 
  rect rect = new rect(left, top, right, bottom); 
  rectf rectf = new rectf(rect); 
 
  paint.setantialias(true); 
  canvas.drawargb(0, 0, 0, 0); 
  paint.setcolor(color); 
  canvas.drawroundrect(rectf, roundpx, roundpx, paint); 
  paint.setxfermode(new porterduffxfermode(porterduff.mode.src_in)); 
  canvas.drawbitmap(bitmap, rect, rect, paint); 
  return output; 
} 


下面再解释下:
由于图片是长方形,所以图片的 宽、高 肯定会有一边要小于另一边,要生成正方形就已最小的一边为基准,再来裁切定位另一边的显示范围
至于圆角的半径则是正方形宽的一半,用过 css 的就知道,画圆很方便 border-radius设为 50% 就可以了,都是一个道理
android 的 ui 真是太繁琐了

矩形画个圆角的代码:

public static bitmap makeroundcorner(bitmap bitmap, int px) 
{ 
  int width = bitmap.getwidth(); 
  int height = bitmap.getheight(); 
  bitmap output = bitmap.createbitmap(width, height, bitmap.config.argb_8888); 
  canvas canvas = new canvas(output); 
  int color = 0xff424242; 
  paint paint = new paint(); 
  rect rect = new rect(0, 0, width, height); 
  rectf rectf = new rectf(rect); 
  paint.setantialias(true); 
  canvas.drawargb(0, 0, 0, 0); 
  paint.setcolor(color); 
  canvas.drawroundrect(rectf, px, px, paint); 
  paint.setxfermode(new porterduffxfermode(porterduff.mode.src_in)); 
  canvas.drawbitmap(bitmap, rect, rect, paint); 
  return output; 
} 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网