Android一行代码实现圆形头像

效果图

在开发APP中,经常要实现圆形头像,那么该如何实现呢?

要裁剪吗,要重写draw函数吗?不用,只用一行代码就可以实现

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一行代码实现圆形头像 的全部内容, 来源链接: utcz.com/z/324907.html

回到顶部