Android自定义View训练【1】

前言:最近这段时间想根据网上博客的案例,自己练习自定义View,代码仅仅作为练习用,还有很多不足之处,见谅

案例取自:http://blog.csdn.net/wingichoy/article/details/50455412


先上传源码

public class PracticeView1 extends View {

    private float mrectwidth = 200;
    private float mrectheight = 100;
    private float mround = 20;
    private float len = 15;

    private Paint mPaint = new Paint();
    private Path mPath = new Path();
    public PracticeView1(Context context) {
        super(context);
    }

    public PracticeView1(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int mwidthmode = MeasureSpec.getMode(widthMeasureSpec);
        int mwidthsize = MeasureSpec.getSize(widthMeasureSpec);
        int mheightmode = MeasureSpec.getMode(heightMeasureSpec);
        int mheightsize = MeasureSpec.getSize(heightMeasureSpec);

        mrectwidth = (float) mwidthsize;
        mrectheight = (float) mheightsize;

        if(mwidthmode == MeasureSpec.AT_MOST) {
            mrectwidth = (float) (600/2);
        }
        if(mheightmode == MeasureSpec.AT_MOST) {
            mrectheight = (float) (300/2);
        }

        setMeasuredDimension((int) mrectwidth, (int) mrectheight);
        Log.d("SunJ:", "mrectwidth " + String.valueOf(mrectwidth) + ",  mrectheight " + String.valueOf(mrectheight));

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPaint.setColor(Color.GRAY);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setAntiAlias(true);
        RectF mRectF = new RectF(0, 0, mrectwidth, mrectheight-len);
        canvas.drawRoundRect(mRectF, mround, mround, mPaint);
        mPath.moveTo(mrectwidth/2, mrectheight);
        mPath.lineTo(mrectwidth/2+len, mrectheight-len);
        mPath.lineTo(mrectwidth/2-len, mrectheight-len);
        mPath.close();
        canvas.drawPath(mPath, mPaint);
    }
}


效果图:



要点:

1.重写onMeasure()是为了在xml中设置layout_weight/layout_height属性为wrap_content时,不会变成match_parent

2.在onDraw()里面的矩形尺寸是由onMeasure()来得到的,这样子,在xml中设置具体的宽和高时,该矩形的大小同样也会发生相应的变化,这样,才能做到随意改变大小;而不会出现当设置具体的宽和高时,view缺胳膊少腿或者是多出空白的区域



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值