效果圖

在開發(fā)APP中,經(jīng)常要實(shí)現(xiàn)圓形頭像,那么該如何實(shí)現(xiàn)呢?
要裁剪嗎,要重寫draw函數(shù)嗎?不用,只用一行代碼就可以實(shí)現(xiàn)
Glide實(shí)現(xiàn)圓形圖像
Glide.with(mContext) .load(R.drawable.iv_image_header) .error(R.drawable.ic_error_default) .transform(new GlideCircleTransform(mContext)) .into(mImage);
其中l(wèi)oad后為載入的圖像,error后為出錯(cuò)時(shí)載入的圖像,transform是對(duì)其修改,我們也是通過這個(gè)GlideCirTransForm來修改的,使用的話要把mContext替換為你自己的activty,mImage為圖片載入的位置
使用之前的準(zhǔn)備
1.添加項(xiàng)目依賴
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.導(dǎo)入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(); }}完成這兩步,你就可以使用那行代碼完成你自己的圓形頭像啦!
以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時(shí)也希望多多支持武林網(wǎng)!
新聞熱點(diǎn)
疑難解答
圖片精選