Android实现图片圆角控件

绘制圆角图片控件:

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import com.android.volley.toolbox.NetworkImageView;
 
/*【圆角】绘制圆角图片控件
 
* NetworkImageView是Volley提供的一个的类,利用这个类,
* 我们可以更有效率地去从网络去获取图片,
* 因为它里面帮我们多设置了一个缓存,帮我们自己去处理请求的队列。
* 请自行度娘下载volley.jar。
* 如果只是加载本地drawable或者mipmap的图片,可以直接继承ImageView
*/     
public class RoundCornerImageView extends NetworkImageView {
      
    public RoundCornerImageView(Context context) {
 
        super(context);        
    }
 
    public RoundCornerImageView(Context context, AttributeSet attrs) {
 
        super(context, attrs);
 
    }
 
    public RoundCornerImageView(Context context, AttributeSet attrs, int defStyle) {     
        super(context, attrs, defStyle);     
    }
 
    @Override
    protected void onDraw(Canvas canvas) {     
        if (getDrawable() == null) {     
            return;     
        }
        Path clipPath = new Path();
 
        int w = this.getWidth();
 
        //画出15度的圆角效果,15度的圆角比5度、10度更加顺滑        
 
        int h = this.getHeight();
 
        float rx = 15.0f;
 
        float ry = 15.0f;
 
        clipPath.addRoundRect(new RectF(0, 0, w, h), rx, ry, Path.Direction.CW);
        canvas.clipPath(clipPath);
 
        super.onDraw(canvas);
 
    }
}

在布局文件中使用:

<com.swissabl.utils.RoundCornerImageView
    android:id="@+id/id_image_kaquan_name_pic"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:scaleType="centerCrop"
    android:padding="0dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"/>

在Java代码里绑定图片:

public class ImageActivity{
 
    private RequestQueue queue;
 
    private ImageLoader imageLoader;
 
    @Override
 
    protected void onCreate(Bundle savedInstanceState) {
 
        queue = Volley.newRequestQueue(this);
 
        imageLoader = new ImageLoader(queue, new BitmapCache());
 
        RoundCornerImageView id_image_kaquan_name_pic= (RoundCornerImageView)
 
                findViewById(R.id.id_image_kaquan_name_pic);
 
        String url="http://image.xinmin.cn/2012/11/01/20121101105203854339.jpg";
 
        id_image_kaquan_name_pic.setImageUrl(url,imageLoader);
 
    }
 
}

发表回复

后才能评论