안 드 로 이 드 코드 원형 이미지 구현

3107 단어 android원형두상
효과 도

개발 앱 에 서 는 원형 얼굴 을 자주 구현 해 야 하 는데 어떻게 구현 해 야 할 까.
재단 하 시 겠 습 니까?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 를 자신의 activey 로 바 꾸 고 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();
 }
}
이 두 단 계 를 완성 하면 당신 은 그 줄 의 코드 를 사용 하여 당신 의 원형 두상 을 완성 할 수 있 습 니 다!
이상 은 본 고의 모든 내용 입 니 다.본 고의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 도움 이 되 기 를 바 랍 니 다.또한 저 희 를 많이 지지 해 주시 기 바 랍 니 다!

좋은 웹페이지 즐겨찾기