import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Region;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;
public class OvalEdgesImageView extends AppCompatImageView {
private int width;
private Matrix mMatrix;
public OvalEdgesImageView(Context context) {
super(context);
setUp();
}
public OvalEdgesImageView(Context context, AttributeSet attrs) {
super(context, attrs, 0);
setUp();
}
public OvalEdgesImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setUp();
}
@Override
protected void onDraw(Canvas canvas) {
Bitmap b = ((BitmapDrawable) getDrawable()).getBitmap();
// get four circles position and size;
int radius = width / 5 * 4;
int min = width / 5;
int length = min * 3 - min / 2;
Path pathOne = new Path();
pathOne.addCircle(min, length, radius, Path.Direction.CW);
Path pathTwo = new Path();
pathTwo.addCircle(radius, length, radius, Path.Direction.CW);
Path pathThree = new Path();
pathThree.addCircle(length, min, radius, Path.Direction.CW);
Path pathFour = new Path();
pathFour.addCircle(length, radius, radius, Path.Direction.CW);
// Merge the circle, take the intersection point
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
pathOne.op(pathTwo, Path.Op.INTERSECT);
pathThree.op(pathFour, Path.Op.INTERSECT);
pathOne.op(pathThree, Path.Op.INTERSECT);
canvas.clipPath(pathOne);
} else {
canvas.clipPath(pathOne, Region.Op.INTERSECT);
canvas.clipPath(pathTwo, Region.Op.INTERSECT);
canvas.clipPath(pathThree, Region.Op.INTERSECT);
canvas.clipPath(pathFour, Region.Op.INTERSECT);
}
//Set bitmap and scale
BitmapShader mBitmapShader = new BitmapShader(b, Shader.TileMode.CLAMP,
Shader.TileMode.CLAMP);
int bSize = Math.min(b.getWidth(), b.getHeight());
float scale = width * 1.0f / bSize;
mMatrix.setScale(scale, scale);
mBitmapShader.setLocalMatrix(mMatrix);
//Draw
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(mBitmapShader);
canvas.drawPath(pathOne, paint);
}
private void setUp() {
mMatrix = new Matrix();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
width = getMeasuredWidth();
}
@Override
public ScaleType getScaleType() {
return ScaleType.CENTER_CROP;
}
}
加载图片后是这样,但是有看到毛边,有想用的可拿去用,有建议的,欢迎留言.
Android自定义椭圆边尖角矩形
最新推荐文章于 2021-05-26 07:16:20 发布