java.lang.IndexOutOfBoundsException and drawPosText
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()上面,觉得不太对劲,看了下源码,额。。。。。。, 意思是干嘛呢,drawPosText()不是第一个参数是字符串嘛,drawPosText()这个方法就是把这个字符串拆成一个一个字符,按顺序对应好第二个参数的位置放好。。。,也就是说我第二个参数offset这个数组长度是10,即包含着五个xy坐标对,只能描述五个位置,所以第一个参数只能是一个五字符的字符串,不然就跟数组不匹配,便会报错了。。。 喏,第一个参数改成是一个五字符的字符串: 也便成功运行了: