android 自定义心形,android使用贝塞尔曲线自定义心形View

贝塞尔曲线(Bézier curve),又称贝兹曲线或贝济埃曲线,是应用于二维图形应用程序的数学曲线。

绘制心形需要Path类中的两个方法分别是:

moveTo(float x,float y) 贝塞尔曲线的起始位置,

cubicTo(float x1, float y1, float x2, float y2, float x3, float y3)

Add a cubic bezier from the last point, approaching control points (x1,y1) and (x2,y2), and ending at (x3,y3).

添加两个控制点(x1,y1),(x2,y2)终点是(x3,y3)

代码:

import android.content.Context;

import android.content.res.TypedArray;

import android.graphics.Canvas;

import android.graphics.Color;

import android.graphics.Paint;

import android.graphics.Path;

import android.util.AttributeSet;

import android.view.View;

/**

* Created by dell on 2016/5/26.

*/

public class HeartView extends View {

private int mMeasureWidth;

private int mWidthMode;

private int mMeasureHeight;

private int mHeightMode;

private Paint paint;

private int heartColor;

public HeartView(Context context){

super(context);

}

public HeartView(Context context,AttributeSet attrs){

super(context,attrs);

TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.HeartView);

heartColor = ta.getColor(R.styleable.HeartView_heartColor, Color.BLUE);

ta.recycle();

}

public HeartView(Context context,AttributeSet attrs,int defStyleAttrs){

super(context,attrs,defStyleAttrs);

}

@Override

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

mWidthMode = MeasureSpec.getMode(widthMeasureSpec);

mHeightMode = MeasureSpec.getMode(heightMeasureSpec);

mMeasureWidth = MeasureSpec.getSize(widthMeasureSpec);

mMeasureHeight = MeasureSpec.getSize(heightMeasureSpec);

if(mWidthMode == MeasureSpec.AT_MOST && mHeightMode == MeasureSpec.AT_MOST){

setMeasuredDimension(200,200);

}else if(mWidthMode == MeasureSpec.AT_MOST){

setMeasuredDimension(200,mMeasureHeight);

}else if(mHeightMode == MeasureSpec.AT_MOST){

setMeasuredDimension(mMeasureWidth,200);

}else{

setMeasuredDimension(mMeasureWidth,mMeasureHeight);

}

}

@Override

protected void onDraw(Canvas canvas) {

super.onDraw(canvas);

paint = new Paint();

paint.setStrokeWidth(6);

paint.setAntiAlias(true);

paint.setColor(heartColor);

int width = getWidth();

int height = getHeight();

// 绘制心形

Path path = new Path();

path.moveTo(width/2,height/4);

path.cubicTo((width*6)/7,height/9,(width*12)/13,(height*2)/5,width/2,(height*7)/12);

canvas.drawPath(path,paint);

Path path2 = new Path();

path2.moveTo(width/2,height/4);

path2.cubicTo(width / 7, height / 9, width / 13, (height * 2) / 5, width / 2, (height * 7) / 12);

canvas.drawPath(path2,paint);

}

}

该HeartView有一个自定义属性heartColor

定义一个attrs.xml文件在里面编写

把HeartView当做普通VIew控件使用,在引用时注意要用包的全名 运行效果图

08fc18748e0b0b8a4bf729d986d73afa.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值