效果图:
说明:
1、我用Android Studio开发的;
2、包名是:package=”com.chen”
3、上图中:
第一张设置类型是矩形,圆角度数是5dp;
第二张设置类型是矩形,圆角度数是20dp;
第三张不设置自定义属性,都用默认的
第四张不设置类型,仅圆角度数是20dp;
第五张设置类型是圆形,圆角度数是20dp;
结论:只有设置类型是矩形的时候,圆角度数才有效;如果不设置或者设置类型是圆形,圆角度数无效,会固定显示圆形
源码:
在res的values文件夹下的attrs.xml文件中(没有的话,创建一个attrs.xml)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="RoundImageView">
<attr name="radiusDimension" format="dimension"/>
<attr name="iamgeType" format="integer"/>
</declare-styleable>
</resources>
RoundView
package com.chen;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.ImageView;
public class RoundView extends ImageView {
/**
* 图片的类型,圆形or圆角
*/
private int type;
public static final int TYPE_CIRCLE = 0;
public static final int TYPE_ROUND = 1;
/**
* 圆角大小的默认值
*/
private static final int BODER_RADIUS_DEFAULT = 10;
/**
* 圆角的大小
*/
private int mBorderRadius;
/**
* 绘图的Paint
*/
private Paint mBitmapPaint;
/**
* 圆角的半径
*/
private int mRadius;
/**
* 3x3 矩阵,主要用于缩小放大
*/
private Matrix mMatrix;
/**
* 渲染图像,使用图像为绘制图形着色
*/
private BitmapShader mBitmapShader;
/**
* view的宽度
*/
private int mWidth;
private RectF mRoundRect;
public RoundView(Context context) {
this(context, null);
}
public RoundView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RoundView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mMatrix = new Matrix();
mBitmapPaint = new Paint();
mBitmapPaint.setAntiAlias(true);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.RoundImageView);
/*
这个方法是转变为标准尺寸的一个函数,例如
int size = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, context.getResources().getDisplayMetrics());
这里COMPLEX_UNIT_SP是单位,20是数值,也就是20sp。
*/
mBorderRadius = a.getDimensionPixelSize(
R.styleable.RoundImageView_radiusDimension, (int) TypedValue
.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
BODER_RADIUS_DEFAULT, getResources()
.getDisplayMetrics()));// 默认为10dp
type = a.getInt(R.styleable.RoundImageView_iamgeType, TYPE_CIRCLE);//默认圆形
a.recycle();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// 圆角图片的范围
if (type == TYPE_ROUND)
mRoundRect = new RectF(0, 0, w, h);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
/**
* 如果类型是圆形,则强制改变view的宽高一致,以小值为准
*/
if (type == TYPE_CIRCLE) {
mWidth = Math.min(getMeasuredWidth(), getMeasuredHeight());
mRadius = mWidth / 2;
setMeasuredDimension(mWidth, mWidth);
}
}
@Override
protected void onDraw(Canvas canvas) {
if (getDrawable() == null) {
return;
}
setUpShader();
if (type == TYPE_ROUND) {
canvas.drawRoundRect(mRoundRect, mBorderRadius, mBorderRadius,
mBitmapPaint);
} else {
canvas.drawCircle(mRadius, mRadius, mRadius, mBitmapPaint);
}
}
/**
* 初始化BitmapShader
*/
private void setUpShader() {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
Bitmap bmp = drawableToBitamp(drawable);
// 将bmp作为着色器,就是在指定区域内绘制bmp
mBitmapShader = new BitmapShader(bmp, TileMode.CLAMP, TileMode.CLAMP);
float scale = 1.0f;
if (type == TYPE_CIRCLE) {
// 拿到bitmap宽或高的小值
int bSize = Math.min(bmp.getWidth(), bmp.getHeight());
scale = mWidth * 1.0f / bSize;
} else if (type == TYPE_ROUND) {
if (!(bmp.getWidth() == getWidth() && bmp.getHeight() == getHeight())) {
// 如果图片的宽或者高与view的宽高不匹配,计算出需要缩放的比例;缩放后的图片的宽高,一定要大于我们view的宽高;所以我们这里取大值;
scale = Math.max(getWidth() * 1.0f / bmp.getWidth(),
getHeight() * 1.0f / bmp.getHeight());
}
}
// shader的变换矩阵,我们这里主要用于放大或者缩小
mMatrix.setScale(scale, scale);
// 设置变换矩阵
mBitmapShader.setLocalMatrix(mMatrix);
// 设置shader
mBitmapPaint.setShader(mBitmapShader);
}
/**
* drawable转bitmap
*
* @param drawable
* @return
*/
private Bitmap drawableToBitamp(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bd = (BitmapDrawable) drawable;
return bd.getBitmap();
}
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();
Utils.printLogData("==w==" + w);
Utils.printLogData("==h==" + h);
try {
Bitmap bitmap = Bitmap.createBitmap(w, h, drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
drawable.draw(canvas);
return bitmap;
} catch (OutOfMemoryError outOfMemoryError) {
System.gc();
//返回一个默认的
return BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
}
}
private static final String STATE_INSTANCE = "state_instance";
private static final String STATE_TYPE = "state_type";
private static final String STATE_BORDER_RADIUS = "state_border_radius";
@Override
protected Parcelable onSaveInstanceState() {
Bundle bundle = new Bundle();
bundle.putParcelable(STATE_INSTANCE, super.onSaveInstanceState());
bundle.putInt(STATE_TYPE, type);
bundle.putInt(STATE_BORDER_RADIUS, mBorderRadius);
return bundle;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (state instanceof Bundle) {
Bundle bundle = (Bundle) state;
super.onRestoreInstanceState(((Bundle) state)
.getParcelable(STATE_INSTANCE));
this.type = bundle.getInt(STATE_TYPE);
this.mBorderRadius = bundle.getInt(STATE_BORDER_RADIUS);
} else {
super.onRestoreInstanceState(state);
}
}
public void setBorderRadius(int borderRadius) {
int pxVal = dp2px(borderRadius);
if (this.mBorderRadius != pxVal) {
this.mBorderRadius = pxVal;
invalidate();
}
}
public void setType(int type) {
if (this.type != type) {
this.type = type;
if (this.type != TYPE_ROUND && this.type != TYPE_CIRCLE) {
this.type = TYPE_CIRCLE;
}
requestLayout();
}
}
private int dp2px(int dpVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dpVal, getResources().getDisplayMetrics());
}
}
布局中使用:
第一种用法:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#55ff0000"
android:orientation="vertical"
>
<com.chen.RoundView
android:id="@+id/rv_1"
xmlns:sing="http://schemas.android.com/apk/res/com.chen"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:background="#ffffff"
android:src="@mipmap/ch"
sing:iamgeType="1"
sing:radiusDimension="5dp"/>
<com.chen.RoundView
xmlns:sing="http://schemas.android.com/apk/res/com.chen"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:background="#ffffff"
android:src="@mipmap/ch"
sing:iamgeType="1"
sing:radiusDimension="20dp"/>
<com.chen.RoundView
xmlns:sing="http://schemas.android.com/apk/res/com.chen"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:background="#ffffff"
android:src="@mipmap/ch"
/>
<com.chen.RoundView
xmlns:sing="http://schemas.android.com/apk/res/com.chen"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:background="#ffffff"
android:src="@mipmap/ch"
sing:radiusDimension="20dp"
/>
<com.chen.RoundView
xmlns:sing="http://schemas.android.com/apk/res/com.chen"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:background="#ffffff"
android:src="@mipmap/ch"
sing:iamgeType="0"
sing:radiusDimension="20dp"
/>
</LinearLayout>
第二种用法:
讲自定义属性加在根布局上
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:sing="http://schemas.android.com/apk/res-auto/com.chen"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#55ff0000"
android:orientation="vertical"
>
<com.chen.RoundView
android:id="@+id/rv_1"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:background="#ffffff"
android:src="@mipmap/ch"
sing:iamgeType="1"
sing:radiusDimension="5dp"/>
<com.chen.RoundView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:background="#ffffff"
android:src="@mipmap/ch"
sing:iamgeType="1"
sing:radiusDimension="20dp"/>
<com.chen.RoundView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:background="#ffffff"
android:src="@mipmap/ch"
/>
<com.chen.RoundView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:background="#ffffff"
android:src="@mipmap/ch"
sing:radiusDimension="20dp"
/>
<com.chen.RoundView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:background="#ffffff"
android:src="@mipmap/ch"
sing:iamgeType="0"
sing:radiusDimension="20dp"
/>
</LinearLayout>
有时候会出现提示(但是不影响运行):
摘录及翻译如下:
Suspicious可疑的多疑的 namespace命名空间: Did you mean http://schemas.android.com/apk/res-auto? less... (Ctrl+F1)
In Gradle projects设计, the actual真实的,实际的 package used in the final APK can vary变化;
for example,you can add a .debug package suffix后缀 in one version and not the other.
Therefore因此, you should not hardcode硬编码 the application package in the resource资源;
instead代替, use the special特别的、专门的 namespace http://schemas.android.com/apk/res-auto which will cause the tools
to figure绘制 out the right namespace for the resource regardless不管 of the actual package used during the build.
activity中:
package com.chen;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity3 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_33);
// RoundView rv_1 = (RoundView) findViewById(R.id.rv_1);
// rv_1.setType(1);
// rv_1.setBorderRadius(30);
}
}