java.lang.IndexOutOfBoundsException and drawPosText

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值