Android应用中在对头像进行圆形处理

本篇文章给大家分享的是有关Android应用中在对头像进行圆形处理,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

Glide实现圆形图像

Glide.with(mContext)
  .load(R.drawable.iv_image_header)
  .error(R.drawable.ic_error_default)
  .transform(new GlideCircleTransform(mContext))
  .into(mImage);

其中load后为载入的图像,error后为出错时载入的图像,transform是对其修改,我们也是通过这个GlideCirTransForm来修改的,使用的话要把mContext替换为你自己的activty,mImage为图片载入的位置

使用之前的准备

1.添加项目依赖

compile 'org.greenrobot:eventbus:3.0.0'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'org.jetbrains:annotations-java5:15.0'
compile 'in.srain.cube:ultra-ptr:1.0.11'
compile 'com.wang.avi:library:1.0.5'

2.导入GlideCircleTransform.java文件

GlideCircleTransform.java代码如下:

package com.sina.weibo.sdk.demo.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;

public class GlideCircleTransform extends BitmapTransformation {

 public GlideCircleTransform(Context context) {
  super(context);
 }

 @Override
 protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
  return circleCrop(pool, toTransform);
 }

 private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
  if (source == null) return null;

  int size = Math.min(source.getWidth(), source.getHeight());
  int x = (source.getWidth() - size) / 2;
  int y = (source.getHeight() - size) / 2;

  Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);

  Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
  if (result == null) {
   result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
  }

  Canvas canvas = new Canvas(result);
  Paint paint = new Paint();
  paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
  paint.setAntiAlias(true);
  float r = size / 2f;
  canvas.drawCircle(r, r, r, paint);
  return result;
 }
 @Override
 public String getId() {
  return getClass().getName();
 }
}

以上就是Android应用中在对头像进行圆形处理,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注行业资讯频道。