Android 图片设置圆角

By | 2019年8月26日

  Android中经常会遇到对图片进行二次处理,例如加圆角,或者显示圆形图片

       方法一:

  通过第三方框架Glide实现图片显示有圆角,有三种写法如下:

  1.1,第一种实现:

  RequestOptions options = new RequestOptions().error(R.drawable.img_load_failure).bitmapTransform(new RoundedCorners(30));//图片圆角为30

  Glide.with(this).load(URL) //图片地址

  .apply(options)

  .into(ImagView);

  1.2,第二种实现:

  RequestOptions requestOptions = new RequestOptions();

  requestOptions.placeholder(R.drawable.ic_launcher_background);

  requestOptions.circleCropTransform();

  requestOptions.transforms( new RoundedCorners(30));

  Glide.with(this).load(URL) //图片地址

  .apply(options)

  .into(ImagView);

  1.3,第三种实现:

  RequestOptions options = new RequestOptions().centerCrop() .transform(new RoundTransform(this,30));

  Glide.with(this).load(URL) //图片地址

  .apply(options)

  .into(ImagView);

  public class RoundTransform extends BitmapTransformation {

  private static float radius = 0f;

  public RoundTransform(Context context) {

  this(context, 4);

  }

  public RoundTransform(Context context, int dp) {

  super(context);

  this.radius = Resources.getSystem().getDisplayMetrics().density * dp;

  }

  @Override

  protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {

  Bitmap bitmap = TransformationUtils.centerCrop(pool, toTransform, outWidth, outHeight);

  return roundCrop(pool, bitmap);

  }

  private static Bitmap roundCrop(BitmapPool pool, Bitmap source) {

  if (source == null) return null;

  Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);

  if (result == null) {

  result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);

  } 无锡人流多少钱 http://www.bhnfkyy.com

  Canvas canvas = new Canvas(result);

  Paint paint = new Paint();

  paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));

  paint.setAntiAlias(true);

  RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());

  canvas.drawRoundRect(rectF, radius, radius, paint);

  return result;

  }

  public String getId() {

  return getClass().getName() + Math.round(radius);

  }

  @Override

  public void updateDiskCacheKey(MessageDigest messageDigest) {

  }

  }

发表评论