美文网首页
2020-04-13

2020-04-13

作者: Jian_98 | 来源:发表于2020-04-13 15:57 被阅读0次

    布局

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="10dp">
        <ImageView
            android:id="@+id/image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:src="@drawable/ic_launcher_background" />
        <EditText
            android:id="@+id/et"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:hint="输入验证码" />
        <Button
            android:id="@+id/btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="获得验证码" />
        <Button
            android:id="@+id/btn_submit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="提交" />
    </LinearLayout>
    

    代码:

    import android.graphics.Bitmap;
    import android.text.TextUtils;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ImageView;
    import android.widget.Toast;
    
    import com.jinshanjf.mxyinhao.R;
    import com.jinshanjf.mxyinhao.other.ui.BaseFragment;
    import com.jinshanjf.mxyinhao.other.util.CodeUtils;
    
    /**
     * Created by lcw on 2018/4/24.
     */
    
    public class MineFragment extends BaseFragment implements View.OnClickListener {
        private ImageView image;
        private EditText et;
        private Button btn, submit;
        private String codeStr;
        private CodeUtils codeUtils;
    
        @Override
        protected int getViewById() {
            return R.layout.fragment_mine;
        }
    
        @Override
        protected void initView() {
            image = view.findViewById(R.id.image);
            et = view.findViewById(R.id.et);
            btn = view.findViewById(R.id.btn);
            submit = view.findViewById(R.id.btn_submit);
            btn.setOnClickListener(this);
            submit.setOnClickListener(this);
            getCode();
        }
    
        @Override
        protected void initDate() {
    
        }
    
        @Override
        protected void initEvent() {
    
        }
    
        //获取验证码
        private void getCode() {
            codeUtils = CodeUtils.getInstance();
            Bitmap bitmap = codeUtils.createBitmap();
            image.setImageBitmap(bitmap);
        }
    
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn:
                    getCode();
                    break;
                case R.id.btn_submit:
                    codeStr = et.getText().toString().trim();
                    Log.e("codeStr", codeStr);
                    if (null == codeStr || TextUtils.isEmpty(codeStr)) {
                        Toast.makeText(getContext(), "请输入验证码", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    String code = codeUtils.getCode();
                    Log.e("code", code);
                    if (code.equalsIgnoreCase(codeStr)) {
                        Toast.makeText(getContext(), "验证码正确", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getContext(), "验证码错误", Toast.LENGTH_SHORT).show();
                        getCode();
                    }
                    break;
                default:
                    break;
            }
        }
    }
    

    CodeUtils

    import android.graphics.Bitmap;
    import android.graphics.Bitmap.Config;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    
    import java.util.Random;
    
    /**
     *   Created by lcw on 2018/4/24.
     * 用于图片验证码的工具类
     */
    public class CodeUtils {
        private static final char[] CHARS = {
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
                'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
                'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
        };
    
        private static CodeUtils mCodeUtils;
        private int mPaddingLeft, mPaddingTop;
        private StringBuilder mBuilder = new StringBuilder();
        private Random mRandom = new Random();
    
        //Default Settings
        private static final int DEFAULT_CODE_LENGTH = 6;//验证码的长度  这里是6位
        private static final int DEFAULT_FONT_SIZE = 60;//字体大小
        private static final int DEFAULT_LINE_NUMBER = 3;//多少条干扰线
        private static final int BASE_PADDING_LEFT = 20; //左边距
        private static final int RANGE_PADDING_LEFT = 30;//左边距范围值
        private static final int BASE_PADDING_TOP = 70;//上边距
        private static final int RANGE_PADDING_TOP = 15;//上边距范围值
        private static final int DEFAULT_WIDTH = 300;//默认宽度.图片的总宽
        private static final int DEFAULT_HEIGHT = 100;//默认高度.图片的总高
        private static final int DEFAULT_COLOR = 0xDF;//默认背景颜色值
    
        private String code;
    
        public static CodeUtils getInstance() {
            if(mCodeUtils == null) {
                mCodeUtils = new CodeUtils();
            }
            return mCodeUtils;
        }
    
        //生成验证码图片
        public Bitmap createBitmap() {
            mPaddingLeft = 0; //每次生成验证码图片时初始化
            mPaddingTop = 0;
    
            Bitmap bitmap = Bitmap.createBitmap(DEFAULT_WIDTH, DEFAULT_HEIGHT, Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            code = createCode();
            canvas.drawColor(Color.rgb(DEFAULT_COLOR, DEFAULT_COLOR, DEFAULT_COLOR));
            Paint paint = new Paint();
            paint.setTextSize(DEFAULT_FONT_SIZE);
    
            for (int i = 0; i < code.length(); i++) {
                randomTextStyle(paint);
                randomPadding();
                canvas.drawText(code.charAt(i) + "" , mPaddingLeft, mPaddingTop, paint);
            }
            //干扰线
            for (int i = 0; i < DEFAULT_LINE_NUMBER; i++) {
                drawLine(canvas, paint);
            }
            canvas.save(Canvas.ALL_SAVE_FLAG);//保存
            canvas.restore();
            return bitmap;
        }
        /**
         * 得到图片中的验证码字符串
         * @return
         */
        public String getCode() {
            return code;
        }
    
        //生成验证码
        public String createCode() {
            mBuilder.delete(0, mBuilder.length()); //使用之前首先清空内容
            for (int i = 0; i < DEFAULT_CODE_LENGTH; i++) {
                mBuilder.append(CHARS[mRandom.nextInt(CHARS.length)]);
            }
            return mBuilder.toString();
        }
    
        //生成干扰线
        private void drawLine(Canvas canvas, Paint paint) {
            int color = randomColor();
            int startX = mRandom.nextInt(DEFAULT_WIDTH);
            int startY = mRandom.nextInt(DEFAULT_HEIGHT);
            int stopX = mRandom.nextInt(DEFAULT_WIDTH);
            int stopY = mRandom.nextInt(DEFAULT_HEIGHT);
            paint.setStrokeWidth(1);
            paint.setColor(color);
            canvas.drawLine(startX, startY, stopX, stopY, paint);
        }
    
        //随机颜色
        private int randomColor() {
            mBuilder.delete(0, mBuilder.length()); //使用之前首先清空内容
            String haxString;
            for (int i = 0; i < 3; i++) {
                haxString = Integer.toHexString(mRandom.nextInt(0xFF));
                if (haxString.length() == 1) {
                    haxString = "0" + haxString;
                }
                mBuilder.append(haxString);
            }
            return Color.parseColor("#" + mBuilder.toString());
        }
    
        //随机文本样式
        private void randomTextStyle(Paint paint) {
            int color = randomColor();
            paint.setColor(color);
            paint.setFakeBoldText(mRandom.nextBoolean());  //true为粗体,false为非粗体
            float skewX = mRandom.nextInt(11) / 10;
            skewX = mRandom.nextBoolean() ? skewX : -skewX;
            paint.setTextSkewX(skewX); //float类型参数,负数表示右斜,整数左斜
    //        paint.setUnderlineText(true); //true为下划线,false为非下划线
    //        paint.setStrikeThruText(true); //true为删除线,false为非删除线
        }
    
        //随机间距
        private void randomPadding() {
            mPaddingLeft += BASE_PADDING_LEFT + mRandom.nextInt(RANGE_PADDING_LEFT);
            mPaddingTop = BASE_PADDING_TOP + mRandom.nextInt(RANGE_PADDING_TOP);
        }
    }
    

    转自https://www.jianshu.com/p/7321d52fa66f
    为自己保留一份,感谢作者。

    相关文章

      网友评论

          本文标题:2020-04-13

          本文链接:https://www.haomeiwen.com/subject/lvfnmhtx.html