自定義ImageView完成圓形頭像自定義
##前言 我們可以看到現在的好多app的頭像都是圓形的,記得應該是一年之前吧,具體的時間也不記得了,那個時候更新飛信,那次改版挺大,頭像是圓形的,感覺挺不錯的。那麼今天也來實現以下吧。 ###我們來分析一下,怎麼去實現
- 第一步:我們應該知道顯示的頭像是一個imageview,那麼我們就繼承ImageView
- 第二步:它有自己的自定義屬性(外部有一個大小可以變的圓,顏色也可以變化) ###接下來我們來實現吧
- 首先要來看看他有的自定義屬性 attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CircleImageView">
<attr name="outCircleColor" format="color"/>
<attr name="outCircleWidth" format="dimension"/>
</declare-styleable>
</resources>
複製程式碼
- 來實現自定義的ImageView: 這裡面也沒有多少的程式碼,在這裡用到的測量寬高,繪製圓,程式碼裡面都有了註釋。
package com.example.headimage;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.widget.ImageView;
/**
* Created by 若蘭 on 2016/2/13.
* 一個懂得了程式設計樂趣的小白,希望自己
* 能夠在這個道路上走的很遠,也希望自己學習到的
* 知識可以幫助更多的人,分享就是學習的一種樂趣
* QQ:1069584784
* csdn:http://blog.csdn.net/wuyinlei
*/
public class CircleImageView extends ImageView {
//外圓的寬度
private int outCircleWidth;
//外圓的顏色
private int outCircleColor = Color.WHITE;
//畫筆
private Paint paint;
//view的寬度和高度
private int viewWidth;
private int viewHeigth;
private Bitmap image;
public CircleImageView(Context context) {
this(context, null);
}
public CircleImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initAttrs(context, attrs, defStyleAttr);
}
/**
* 初始化資原始檔
*
* @param context
* @param attrs
* @param defStyleAttr
*/
private void initAttrs(Context context, AttributeSet attrs, int defStyleAttr) {
TypedArray array = null;
if (attrs != null) {
array = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView);
int len = array.length();
for (int i = 0; i < len; i++) {
int attr = array.getIndex(i);
switch (attr) {
//獲取到外圓的顏色
case R.styleable.CircleImageView_outCircleColor:
this.outCircleColor = array.getColor(attr, Color.WHITE);
break;
//獲取到外圓的半徑
case R.styleable.CircleImageView_outCircleWidth:
this.outCircleWidth = (int) array.getDimension(attr, 5);
break;
}
}
}
paint = new Paint();
paint.setColor(outCircleColor);//顏色
paint.setAntiAlias(true);//設定抗鋸齒
array.recycle(); //回收
}
/**
* view的測量
* @param widthMeasureSpec
* @param heightMeasureSpec
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = measureWith(widthMeasureSpec);
int height = measureWith(heightMeasureSpec);
viewWidth = width - outCircleWidth * 2;
viewHeigth = height - outCircleWidth * 2;
//呼叫該方法將測量後的寬和高設定進去,完成測量工作,
setMeasuredDimension(width, height);
}
/**
* 測量寬和高,這一塊可以是一個模板程式碼(Android群英傳)
* @param widthMeasureSpec
* @return
*/
private int measureWith(int widthMeasureSpec) {
int result = 0;
//從MeasureSpec物件中提取出來具體的測量模式和大小
int mode = MeasureSpec.getMode(widthMeasureSpec);
int size = MeasureSpec.getSize(widthMeasureSpec);
if (mode == MeasureSpec.EXACTLY) {
//測量的模式,精確
result = size;
} else {
result = viewWidth;
}
return result;
}
/**
* 繪製
* @param canvas
*/
@Override
protected void onDraw(Canvas canvas) {
//載入圖片
loadImage();
if (image != null) {
//拿到最小的值(這裡我們要去到最小的)
int min = Math.min(viewWidth, viewHeigth);
int circleCenter = min / 2;
image = Bitmap.createScaledBitmap(image, min, min, false);
//畫圓
canvas.drawCircle(circleCenter + outCircleWidth, circleCenter + outCircleWidth, circleCenter + outCircleColor, paint);
//畫影象
canvas.drawBitmap(createCircleBitmap(image, min), outCircleWidth, outCircleWidth, null);
}
}
/**
* 建立一個圓形的bitmap
*
* @param image 傳入的image
* @param min
* @return
*/
private Bitmap createCircleBitmap(Bitmap image, int min) {
Bitmap bitmap = null;
Paint paint = new Paint();
paint.setAntiAlias(true);
bitmap = Bitmap.createBitmap(min, min, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
//畫一個和圖片大小相等的畫布
canvas.drawCircle(min / 2, min / 2, min / 2, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(image, 0, 0, paint);
return bitmap;
}
/**
* 載入Image
*/
private void loadImage() {
BitmapDrawable bitmapDrawable = (BitmapDrawable) this.getDrawable();
if (bitmapDrawable != null) {
image = bitmapDrawable.getBitmap();
}
}
/**
* 對外提供的可以設定外圓的顏色的方法
* @param outCircleColor
*/
public void setOutCircleColor(int outCircleColor) {
if (null != paint) {
paint.setColor(outCircleColor);
}
this.invalidate();
}
/**
* 對外提供給的設定外圓的寬度大小的方法
* @param outCircleWidth
*/
public void setOutCircleWidth(int outCircleWidth) {
this.outCircleWidth = outCircleWidth;
this.invalidate();
}
}
複製程式碼
我們來看下效果圖:
好了,這裡我在新增一些功能吧,就是可以選擇相簿圖片,可以呼叫系統相機,在使用圖片的時候可以裁剪。我們點選的時候用到了PopupWindow。這些程式碼都很簡單(我以為還有點知識點,結果被鄙視了。。。)package com.example.headimage;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Toast;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private CircleImageView ivHead;
private RelativeLayout layout_choose;
private RelativeLayout layout_photo;
private RelativeLayout layout_close;
private LinearLayout layout_all;
protected int mScreenWidth;
/**
* 定義三種狀態
*/
private static final int REQUESTCODE_PIC = 1;//相簿
private static final int REQUESTCODE_CAM = 2;//相機
private static final int REQUESTCODE_CUT = 3;//圖片裁剪
private Bitmap mBitmap;
private File mFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ivHead = (CircleImageView) findViewById(R.id.iv_head);
layout_all = (LinearLayout) findViewById(R.id.layout_all);
ivHead.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.iv_head:
showMyDialog();
break;
}
}
PopupWindow avatorPop;
private void showMyDialog() {
View view = LayoutInflater.from(this).inflate(R.layout.pop_show_dialog,
null);
layout_choose = (RelativeLayout) view.findViewById(R.id.layout_choose);
layout_photo = (RelativeLayout) view.findViewById(R.id.layout_photo);
layout_close = (RelativeLayout) view.findViewById(R.id.layout_close);
layout_choose.setBackgroundColor(getResources().getColor(
R.color.base_color_text_white));
layout_photo.setBackgroundDrawable(getResources().getDrawable(
R.drawable.pop_bg_press));
layout_close.setBackgroundColor(getResources().getColor(
R.color.base_color_text_white));
layout_photo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
layout_choose.setBackgroundColor(getResources().getColor(
R.color.base_color_text_white));
layout_photo.setBackgroundDrawable(getResources().getDrawable(
R.drawable.pop_bg_press));
layout_close.setBackgroundColor(getResources().getColor(
R.color.base_color_text_white));
openCamera();
// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//startActivityForResult(intent,);
}
});
layout_choose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
layout_photo.setBackgroundColor(getResources().getColor(
R.color.base_color_text_white));
layout_choose.setBackgroundDrawable(getResources().getDrawable(
R.drawable.pop_bg_press));
layout_close.setBackgroundColor(getResources().getColor(
R.color.base_color_text_white));
openPic();
}
});
layout_close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
layout_photo.setBackgroundColor(getResources().getColor(
R.color.base_color_text_white));
layout_close.setBackgroundDrawable(getResources().getDrawable(
R.drawable.pop_bg_press));
layout_choose.setBackgroundColor(getResources().getColor(
R.color.base_color_text_white));
avatorPop.dismiss();
}
});
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
mScreenWidth = metric.widthPixels;
avatorPop = new PopupWindow(view, mScreenWidth, 200);
avatorPop.setTouchInterceptor(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
avatorPop.dismiss();
return true;
}
return false;
}
});
//設定寬度
avatorPop.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
//設定高度
avatorPop.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
//可以點選
avatorPop.setTouchable(true);
avatorPop.setFocusable(true);
avatorPop.setOutsideTouchable(true);
avatorPop.setBackgroundDrawable(new BitmapDrawable());
// 動畫效果 從底部彈起
avatorPop.setAnimationStyle(R.style.Animations_GrowFromBottom);
avatorPop.showAtLocation(layout_all, Gravity.BOTTOM, 0, 0);
}
/**
* 開啟相簿
*/
private void openPic() {
Intent picIntent = new Intent(Intent.ACTION_PICK,null);
picIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
startActivityForResult(picIntent,REQUESTCODE_PIC);
}
/**
* 呼叫相機
*/
private void openCamera() {
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
if (!file.exists()){
file.mkdirs();
}
mFile = new File(file, System.currentTimeMillis() + ".jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);
startActivityForResult(intent,REQUESTCODE_CAM);
} else {
Toast.makeText(this, "請確認已經插入SD卡", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUESTCODE_CAM:
startPhotoZoom(Uri.fromFile(mFile));
break;
case REQUESTCODE_PIC:
if (data == null || data.getData() == null){
return;
}
startPhotoZoom(data.getData());
break;
case REQUESTCODE_CUT:
if (data!= null){
setPicToView(data);
}
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void setPicToView(Intent data) {
Bundle bundle = data.getExtras();
if (bundle != null){
//這裡也可以做檔案上傳
mBitmap = bundle.getParcelable("data");
ivHead.setImageBitmap(mBitmap);
}
}
/**
* 開啟系統圖片裁剪功能
* @param uri
*/
private void startPhotoZoom(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri,"image/*");
intent.putExtra("crop",true);
intent.putExtra("aspectX",1);
intent.putExtra("aspectY",1);
intent.putExtra("outputX",300);
intent.putExtra("outputY",300);
intent.putExtra("scale",true); //黑邊
intent.putExtra("scaleUpIfNeeded",true); //黑邊
intent.putExtra("return-data",true);
intent.putExtra("noFaceDetection",true);
startActivityForResult(intent,REQUESTCODE_CUT);
}
}
複製程式碼
我們來看下效果
裁剪功能: 裁剪後確定: 這裡我們對於動畫,還有資源屬性用到了一些style樣式,還有一些動畫資原始檔,這裡我就不上傳了,直接給git地址,方便下載,檢視更多資源 https://github.com/wuyinlei/CircleImgae