一个跟随屏幕旋转的自定义水印控件

这几天在做一个拍照加水印的功能,开发的过程中要求可以横向拍摄,但是水印也要跟随着屏幕的方向,因为水印显示的是当前的经纬度,总不能说我把手机倒着,让文字也倒着显示吧,所以就要求写一个能跟着屏幕旋转的水印控件。

自定义控件的代码如下:

public class WaterMarkView extends View {

    private Context mContext;
    private String mTime;
    private String mLocation;
    private Paint mPaint;
    private int mDegree;
    private float mPaintTextSize = 16;

    public WaterMarkView(Context context) {
        super(context);
        setWillNotDraw(false);
    }

    public WaterMarkView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setWillNotDraw(false);
        this.mContext = context;
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(mContext.getResources().getColor(R.color.mis_pink));
        mPaint.setTextSize(DisplayUtil.dip2px(mContext, mPaintTextSize));
        mPaint.setFakeBoldText(true);
        mPaint.setShadowLayer(1.6f, 1.5f, 1.3f, Color.BLACK);
    }

    public void setTvTime(String time) {
        this.mTime = time;
    }

    public void setTvLocation(String location) {
        this.mLocation = location;
    }

    public void setDegree(int degree) {
        this.mDegree = degree;
    }

    public void setTextSize(int size) {
        this.mPaintTextSize = size;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = ScreenUtils.getScreenWidth(mContext);
        int height = ScreenUtils.getScreenHeight(mContext);
        Log.i("sherry", "width=" + width + "height=" + height);
        switch (mDegree) {
            case 0:
                canvas.rotate(0);
                canvas.drawText(mTime, 60, height - mPaintTextSize / 16 * 120, mPaint);
                canvas.drawText(mLocation, 60, height - mPaintTextSize / 16 * 60, mPaint);
                break;
            case -90:
                canvas.rotate(-90);
                canvas.translate(-height, 0);
                canvas.drawText(mTime, 120, width - mPaintTextSize / 16 * 120, mPaint);
                canvas.drawText(mLocation, 120, width - mPaintTextSize / 16 * 60, mPaint);
                break;
            case 90:
                canvas.rotate(90);
                canvas.translate(0, -width);
                canvas.drawText(mTime, 120, width - mPaintTextSize / 16 * 120, mPaint);
                canvas.drawText(mLocation, 120, width - mPaintTextSize / 16 * 60, mPaint);
                break;
            case 180:
                canvas.rotate(180, width / 2, height / 2);
                canvas.drawText(mTime, 60, height - mPaintTextSize / 16 * 120, mPaint);
                canvas.drawText(mLocation, 60, height - mPaintTextSize / 16 * 60, mPaint);
                break;
        }
    }
}

项目下载地址:https://download.csdn.net/download/shan286/10417458

你可能感兴趣的:(Android)