View的绘制

来源:互联网 发布:数据库原理与应用pdf 编辑:程序博客网 时间:2024/05/13 06:34

当测量好了一个View后,就可以简单地重写onDraw()方法,并在canvas对象上来绘制所需要的图像;

要在Android中绘制相应的图像,就必须在canvas上进行绘制

执行顺序

onSizeChanged()比onDraw()先执行
在onDraw()方法中调用invalidate()方法通知view进行重绘,将再次执行onDraw()方法,不在执行onSizeChanged()方法
或调用postInvalidateDelayde()
<span style="font-size:18px;">private void initView() {        Log.e("sssss","initView");        mPaint = new Paint();<span style="color:#ff0000;">//首先设置画笔</span>        mPaint.setColor(Color.BLUE);        mPaint.setStyle(Paint.Style.FILL);        mRectCount = 12;    }</span>
<span style="font-size:18px;"><pre name="code" class="java">@Override    protected void onSizeChanged(int w, int h, int oldw, int oldh) {        super.onSizeChanged(w, h, oldw, oldh);        Log.e("sssss","onSizeChanged");        mWidth = getWidth();        mRectHeight = getHeight();<span style="color:#ff0000;">//获得显示在屏幕上的高度及宽度</span>        mRectWidth = (int) (mWidth * 0.6 / mRectCount);        mLinearGradient = new LinearGradient(<span style="color:#ff0000;">//设置渐变</span>                0,                0,                mRectWidth,                mRectHeight,                Color.YELLOW,                Color.BLUE,                Shader.TileMode.CLAMP);        mPaint.setShader(mLinearGradient);<span style="color:#ff0000;">//把特殊效果(渐变)赋给画笔</span>    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        Log.e("sssss","onDraw");        for (int i = 0; i < mRectCount; i++) {            mRandom = Math.random();            float currentHeight = (float) (mRectHeight * mRandom);            canvas.drawRect(                    (float) (mWidth * 0.4 / 2 + mRectWidth * i + offset),                    currentHeight,                    (float) (mWidth * 0.4 / 2 + mRectWidth * (i + 1)),                    mRectHeight,                    mPaint);        }        postInvalidateDelayed(300);    }</span>




0 0
原创粉丝点击