您现在的位置是:首页 > 文章详情

java.lang.IndexOutOfBoundsException and drawPosText

日期:2018-07-30点击:514
img_4ef1fe0f3ef768e511d9d4ed81a03571.png
package com.example.canvastest;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by 700 on 2018/7/31.
 */

public class DrawText_DrawPosText extends View{

    private Paint mTextPaint;
    private float[] offset = new float[10];

    public DrawText_DrawPosText(Context context, AttributeSet attrs,
                        int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

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

    public DrawText_DrawPosText(Context context) {
        super(context);
    }

    private void initView(){
        for(int i = 0; i<10; i+=2){
            offset[i] = 100;
            offset[i+1] = 250+150*i/2;
        }
        mTextPaint = new Paint();
        mTextPaint.setColor(getResources().getColor(
                android.R.color.holo_blue_light
        ));
        mTextPaint.setTextSize(20);//设置文字大小
//        mTextPaint.setTextAlign(Paint.Align.CENTER);//设置居中
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        initView();
        canvas.drawText("hehehehehedadadadadadadada",100,100,mTextPaint);
        canvas.drawPosText("hehehehehedadadadadadadada",offset,mTextPaint);

    }
}

郁闷。。报错的原因是数组超范围了。。
还以为是for语句写错了,看了半天。。。没错啊。。。

后来聚焦在了drawPosText()上面,觉得不太对劲,看了下源码,额。。。。。。,


img_da495b464b3cfb0e23bcc758d99fc656.png

意思是干嘛呢,drawPosText()不是第一个参数是字符串嘛,drawPosText()这个方法就是把这个字符串拆成一个一个字符,按顺序对应好第二个参数的位置放好。。。,也就是说我第二个参数offset这个数组长度是10,即包含着五个xy坐标对,只能描述五个位置,所以第一个参数只能是一个五字符的字符串,不然就跟数组不匹配,便会报错了。。。

喏,第一个参数改成是一个五字符的字符串:

img_7edd5ebee367f3cb2fcdb899568a0042.png

也便成功运行了:
img_d65b88378cc8e1d198adacd83330df71.png

原文链接:https://yq.aliyun.com/articles/686597
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章