椭圆图片

自定义imageview

package com.bwie.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class CircleImagerView extends ImageView {
    private Paint p;

    public CircleImagerView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }
    
    public CircleImagerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        p = new Paint();
    }


    public CircleImagerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        Drawable drawable = getDrawable();
        if(null!=drawable){
            Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
            Bitmap b = getCircleBitmap(bitmap, 14);
            final Rect rectSrc = new Rect(0, 0, b.getWidth(), b.getHeight());
            final Rect rectDest = new Rect(0, 0, getWidth(), getHeight());
            p.reset();
            canvas.drawBitmap(b, rectSrc,rectDest, p);
            
        }else{
            super.onDraw(canvas);
        }
        
    } 


    private Bitmap getCircleBitmap(Bitmap bitmap,int pixels){
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        p.setAntiAlias(true);
        int x = bitmap.getWidth();
        canvas.drawCircle(x/2, x/2, x/2, p);
        p.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, p);
        return output;
    }

}

xml

 <com.bwie.view.CircleImagerView
        android:id="@+id/img"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:src="@drawable/y5" />

 

posted on 2016-06-08 11:12  glj521  阅读(385)  评论(0编辑  收藏  举报