自定义控件-圆角图片简单实现

圆角图片在现在的设计里,是非常常见的了,网上这方面的代码也非常多,


作为初学者,刚好有点时间,就想自己研究一下,


如果要求不高的话,其实还是挺简单的。


效果图:



直接上代码:


package com.example.labcirclebar;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class CircleImageView extends ImageView {
	
	private int mWidth;
	private int mHeight;
	private int mRadius;
	private Paint mBackgroundPaint;
	private Path mPath;
	private Drawable mDrawable = null;

	public CircleImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initPaint();
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		mDrawable = getDrawable() ;
		if(mDrawable==null){
			return;
		}
		mWidth = getWidth();
		mHeight = getHeight();
		mRadius = mWidth < mHeight ? mWidth/2 : mHeight/2;

		// 先画背景
		canvas.drawCircle(mRadius, mRadius, mRadius, mBackgroundPaint);
		// 画一个圆形path,把图片画在画布的圆形上
		canvas.save();
		mPath.addCircle(mRadius, mRadius, mRadius-16, Path.Direction.CCW);
		canvas.clipPath(mPath);
		mDrawable.draw(canvas);
		canvas.restore();
		
	}
	
	/**
	* 设置画笔
	*/
	private void initPaint (){
		mBackgroundPaint = new Paint();
		mBackgroundPaint.setAntiAlias(true);
		mBackgroundPaint.setStyle(Paint.Style.FILL);
		mBackgroundPaint.setStrokeWidth(20);
		mBackgroundPaint.setColor(Color.parseColor("#7FFFFFFF"));
		mPath = new Path();
	}
	
	

}


布局文件,跟ImageView一样

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:custom="http://schemas.android.com/apk/res/com.example.labcirclebar"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="@drawable/splash"
    tools:context="com.example.labcirclebar.MainActivity" >
    
    <com.example.labcirclebar.CircleImageView 
        android:id="@+id/circle_image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/avatar" />

</RelativeLayout>


更多自定义以后用到再研究吧。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值