Skip to content

Instantly share code, notes, and snippets.

@pythoncat1024
Last active August 6, 2019 23:20
Show Gist options
  • Save pythoncat1024/48c6a9f718e499bb63f7677239ddd374 to your computer and use it in GitHub Desktop.
Save pythoncat1024/48c6a9f718e499bb63f7677239ddd374 to your computer and use it in GitHub Desktop.
通过裁切 onDraw 里面的 canvas,让其在绘制内容之前,先裁切出一个圆形。
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.util.AttributeSet;
/**
* 通过裁切 onDraw 里面的 canvas,让其在绘制内容之前,先裁切出一个圆形出来即可!
*/
public class CircleImageView extends android.support.v7.widget.AppCompatImageView {
private Path circlePath;
public CircleImageView(Context context) {
super(context);
}
public CircleImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CircleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int wM = MeasureSpec.getMode(widthMeasureSpec);
int hM = MeasureSpec.getMode(heightMeasureSpec);
int measuredHeight = getMeasuredHeight();
int measuredWidth = getMeasuredWidth();
if (wM != MeasureSpec.EXACTLY && hM != MeasureSpec.EXACTLY) {
// 两个都是未指定
int size = Math.min(measuredWidth, measuredHeight);
setMeasuredDimension(size, size); // 变成正方形
} else if (hM != MeasureSpec.EXACTLY) {
// 宽度是固定的
setMeasuredDimension(measuredWidth, measuredWidth);
} else if (wM != MeasureSpec.EXACTLY) {
// 高度是固定的
setMeasuredDimension(measuredHeight, measuredHeight);
}
}
@Override
protected void onDraw(Canvas canvas) {
if (circlePath == null) {
circlePath = new Path();
}
int x = (getWidth() + getPaddingLeft() - getPaddingRight()) / 2;
int y = (getHeight() + getPaddingTop() - getPaddingBottom()) / 2;
int radius = Math.min((getWidth() - getPaddingLeft() - getPaddingRight()),
(getHeight() - getPaddingTop() - getPaddingBottom())) / 2;
circlePath.addCircle(x, y, radius, Path.Direction.CCW);
// 只有 add 多个才能看出效果
canvas.clipPath(circlePath);
super.onDraw(canvas);
}
}
...
<CircleImageView
android:scaleType="centerCrop" // 不指定这个type的话,如果图片本身长宽不同,会在圆内留空白
android:layout_width="wrap_content"
android:layout_height="200dp"
android:background="@color/colorAccent"
app:srcCompat="@drawable/cute_cat" />
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment