Android自定义View实现简单文字描边功能
本文实例为大家分享了Android实现简单文字描边功能的具体代码,供大家参考,具体内容如下
效果图:
实现代码:
package com.example.zhangyu.myview.widget;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Picture;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.view.View;
import com.example.zhangyu.myview.R;
public class TouchPullView extends View {
//圆的半径
private float mCircleRadius;
private Paint paint;
private Rect rect=new Rect();
private int count;
public TouchPullView(Context context) {
super(context);
init();
}
public TouchPullView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public TouchPullView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public TouchPullView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
/**
* 初始化
*/
private void init() {
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
//设置抗锯齿
paint.setAntiAlias(true);
//设置防抖动
paint.setDither(true);
//设置填充方式
paint.setStyle(Paint.Style.FILL_AND_STROKE);
//View的点击事件
setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
count++;
invalidate();//重新绘制
}
});
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//设置方形画笔,背景。
paint.setColor(Color.YELLOW);
//先绘制底板
canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
float x = getWidth() / 2;
float y = getHeight() / 2;
float offset = getWidth()/6;
//绘制圆形
paint.setColor(Color.GRAY);
mCircleRadius = offset*1.41f;
canvas.drawCircle(x, y, mCircleRadius, paint);
//绘制图片
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.pic1);
if (bitmap != null) {
canvas.drawBitmap(bitmap,null,new RectF(x-offset,y-offset,x+offset,y+offset),paint);
}
//绘制文字外层的文字,边框
String s = String.valueOf(count);
paint.setStrokeWidth(10);
paint.setColor(Color.RED);
paint.setTextSize(100);
paint.getTextBounds(s,0,s.length(),rect);
float textWidth = rect.width();
float textHeight = rect.height();
x = getWidth()/2-textWidth/2;
y = getHeight() / 2+textHeight/2;
canvas.drawText(s, x, y, paint);
//绘制文字
paint.setColor(Color.BLUE);
paint.setStrokeWidth(0);
canvas.drawText(s, x, y, paint);
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
以上是 Android自定义View实现简单文字描边功能 的全部内容, 来源链接: utcz.com/p/241416.html