飞道的博客

一种基于自定义View的贴纸控件Demo

407人阅读  评论(0)

其实就是自定义一套触摸事件规则,加上对Matrix的使用即可。

首先定义基类,首先不同类型的图元,例如Bitmap或者文本,需要的缩放、移动、测量、绘制方式可能都不一致,所以做成抽象函数顶个接口规范,等待子类自己实现:


  
  1. package com.chenjiezhu.waterMarkShape;
  2. import android.graphics.Canvas;
  3. import android.graphics.Paint;
  4. import android.graphics.PointF;
  5. import android.graphics.RectF;
  6. import android.graphics.Shader;
  7. import android.view.MotionEvent;
  8. import java.util.Queue;
  9. import java.util.concurrent.LinkedBlockingQueue;
  10. public abstract class BaseShape {
  11. private PointF mCurrentCenter = new PointF();
  12. private PointF mPrevCurrentCenter = null;
  13. private float mPrevDistance = Float.MIN_VALUE;
  14. private float mAvergeX = 0, mAvergeY = 0;
  15. private int mPrevPointCount = 0;
  16. /**是否已经缩放过**/
  17. private boolean mIsScaled = false;
  18. private Queue<Float> mTouchDistanceQueue = new LinkedBlockingQueue<>();
  19. private PointF mPrevLocation;
  20. /**水印类型**/
  21. public enum ShapeType {
  22. BITMAP,
  23. TEXT
  24. }
  25. private ShapeType mShapeType = null;
  26. public void setmShapeType(ShapeType mShapeType) {
  27. this.mShapeType = mShapeType;
  28. }
  29. public ShapeType getmShapeType() {
  30. Paint paint;
  31. return mShapeType;
  32. }
  33. /**移动代码实现**/
  34. public abstract void translate(float dx, float dy);
  35. /**缩放代码实现**/
  36. public abstract void scale(float scaleXRatio, float scaleYRatio, float scaleCenterX, float scaleCenterY);
  37. /**绘制代码实现**/
  38. public abstract void draw(Canvas canvas);
  39. /**了解显示范围**/
  40. public abstract RectF getRange();
  41. /**设置显示效果**/
  42. public abstract void setPaint(Paint paint, Shader shader);
  43. /**了解缩放量**/
  44. public abstract PointF getScale();
  45. /**了解位置**/
  46. public abstract PointF getXY();
  47. /**触摸处理**/
  48. public boolean touchEvent(MotionEvent event) {
  49. switch (event.getAction()) {
  50. case MotionEvent.ACTION_DOWN:
  51. mPrevDistance = 0;
  52. mPrevPointCount = event.getPointerCount();
  53. //算出移动中心坐标、点间距离
  54. for ( int i = 0; i < event.getPointerCount(); i++) {
  55. mAvergeX += event.getX(i);
  56. mAvergeY += event.getY(i);
  57. if (i + 1 < event.getPointerCount()) {
  58. mPrevDistance += Math.sqrt(Math.pow(event.getX(i + 1) - event.getX(i), 2) + Math.pow(event.getY(i + 1) - event.getY(i), 2));
  59. }
  60. }
  61. mAvergeX /= event.getPointerCount();
  62. mAvergeY /= event.getPointerCount();
  63. mPrevLocation = getXY();
  64. if (mPrevCurrentCenter == null) {
  65. mPrevCurrentCenter = new PointF(mAvergeX, mAvergeY);
  66. } else {
  67. mPrevCurrentCenter.set(mAvergeX, mAvergeY);
  68. }
  69. break;
  70. case MotionEvent.ACTION_MOVE:
  71. mAvergeX = 0;
  72. mAvergeY = 0;
  73. float nowDistance = 0;
  74. //算出移动中心坐标、点间距离
  75. for ( int i = 0; i < event.getPointerCount(); i++) {
  76. mAvergeX += event.getX(i);
  77. mAvergeY += event.getY(i);
  78. if (i + 1 < event.getPointerCount()) {
  79. nowDistance += Math.sqrt(Math.pow(event.getX(i + 1) - event.getX(i), 2) + Math.pow(event.getY(i + 1) - event.getY(i), 2));
  80. }
  81. }
  82. //现在的点间距离 除以 上次点间距离 这次得到缩放比例
  83. mAvergeX /= event.getPointerCount();
  84. mAvergeY /= event.getPointerCount();
  85. if ((mPrevPointCount != event.getPointerCount()) || event.getPointerCount() <= 1 || mPrevPointCount <= 1) { //触摸点数突然改变 或者 触摸点不超过2,不允许缩放
  86. mPrevDistance = nowDistance = 0;
  87. }
  88. //如果缩放数据有效,则进行平均平滑化并且进行缩放
  89. if (mPrevDistance > 0 && nowDistance > 0) {
  90. mTouchDistanceQueue.add(nowDistance / mPrevDistance);
  91. if (mTouchDistanceQueue.size() >= 6) {
  92. Float point[] = new Float[mTouchDistanceQueue.size()];
  93. mTouchDistanceQueue.toArray(point);
  94. float avergDistance = 0;
  95. for ( int i = 0; i < point.length; i++) {
  96. avergDistance += point[i];
  97. }
  98. avergDistance /= point.length;
  99. // scale((float) Math.sqrt(avergDistance), (float) Math.sqrt(avergDistance), mAvergeX, mAvergeY);
  100. scale(( float) Math.sqrt(avergDistance), ( float) Math.sqrt(avergDistance), event.getX( 0), event.getY( 0));
  101. mIsScaled = true;
  102. while (mTouchDistanceQueue.size() > 6) {
  103. mTouchDistanceQueue.poll();
  104. }
  105. }
  106. }
  107. mPrevPointCount = event.getPointerCount();
  108. mPrevDistance = nowDistance;
  109. //当前坐标 - 上次坐标 = 偏移值,然后进行位置偏移
  110. if (mPrevCurrentCenter == null) {
  111. mPrevCurrentCenter = new PointF(mAvergeX, mAvergeY);
  112. } else {
  113. if (!mIsScaled && event.getPointerCount() == 1) {
  114. translate(mAvergeX - mPrevCurrentCenter.x, mAvergeY - mPrevCurrentCenter.y);
  115. }
  116. mPrevCurrentCenter.set(mAvergeX, mAvergeY);
  117. }
  118. break;
  119. case MotionEvent.ACTION_UP:
  120. //抬起,清理干净数据
  121. mAvergeX = 0;
  122. mAvergeY = 0;
  123. mTouchDistanceQueue.clear();
  124. mIsScaled = false;
  125. break;
  126. }
  127. return true;
  128. }
  129. }

Bitmap类型子类,通过matrix控制图片移动:


  
  1. package com.chenjiezhu.waterMarkShape;
  2. import android.graphics.Bitmap;
  3. import android.graphics.Canvas;
  4. import android.graphics.Matrix;
  5. import android.graphics.Paint;
  6. import android.graphics.PointF;
  7. import android.graphics.RectF;
  8. import android.graphics.Shader;
  9. public class BitmapShape extends BaseShape {
  10. private Matrix mMatrix;
  11. private Bitmap mBitmap;
  12. private RectF mRange;
  13. public BitmapShape() {
  14. setmShapeType(ShapeType.BITMAP);
  15. mMatrix = new Matrix();
  16. }
  17. public void setmBitmap(Bitmap b) {
  18. this.mBitmap = b;
  19. }
  20. @Override
  21. public void translate(float dx, float dy) {
  22. mMatrix.postTranslate(dx, dy);
  23. }
  24. @Override
  25. public void scale(float scaleXRatio, float scaleYRatio, float scaleCenterX, float scaleCenterY) {
  26. mMatrix.postScale(scaleXRatio, scaleYRatio, scaleCenterX, scaleCenterY);
  27. }
  28. @Override
  29. public void draw(Canvas canvas) {
  30. if (mBitmap != null) {
  31. canvas.drawBitmap(mBitmap, mMatrix, null);
  32. //debug code:
  33. // Paint paint = new Paint();
  34. // paint.setStrokeWidth(5f);
  35. // paint.setColor(Color.RED);
  36. // paint.setStyle(Paint.Style.STROKE);
  37. // canvas.drawRect(getRange(), paint);
  38. }
  39. }
  40. @Override
  41. public RectF getRange() {
  42. //cjz: you can see this to know why I do that:https://www.jianshu.com/p/c83f59613c18
  43. float matrix[] = new float[ 9];
  44. mMatrix.getValues(matrix);
  45. mRange = new RectF(
  46. matrix[ 2],
  47. matrix[ 5],
  48. matrix[ 2] + mBitmap.getWidth() * matrix[ 0],
  49. matrix[ 5] + mBitmap.getHeight() * matrix[ 4]);
  50. return mRange;
  51. }
  52. @Override
  53. public void setPaint(Paint paint, Shader shader) {
  54. }
  55. @Override
  56. public PointF getScale() {
  57. float matrix[] = new float[ 9];
  58. mMatrix.getValues(matrix);
  59. return new PointF(matrix[ 0], matrix[ 4]);
  60. }
  61. @Override
  62. public PointF getXY() {
  63. float matrix[] = new float[ 9];
  64. mMatrix.getValues(matrix);
  65. return new PointF(matrix[ 2] + (mBitmap.getWidth() * matrix[ 0]) / 2f, matrix[ 5] + (mBitmap.getHeight() * matrix[ 4]) / 2f);
  66. }
  67. }

 

 

 

文本子类,较为复杂,因为文本不能直接应用Matrix进行形变,所以通过绘制时对Canvas应用Matrix进行调整来实现该功能。难点在于测量方面,大小的计算是通过字符量×画笔大小×缩放量确定的,这样确定的图元范围实测可以准确根据移动位置和缩放大小进行精确调整。


  
  1. package com.chenjiezhu.waterMarkShape;
  2. import android.graphics.Canvas;
  3. import android.graphics.Color;
  4. import android.graphics.Matrix;
  5. import android.graphics.Paint;
  6. import android.graphics.PointF;
  7. import android.graphics.RectF;
  8. import android.graphics.Shader;
  9. public class TextShape extends BaseShape {
  10. private String mText;
  11. private Matrix mMatrix;
  12. private Paint mPaint;
  13. private RectF mRange;
  14. public TextShape() {
  15. mMatrix = new Matrix();
  16. }
  17. public void setText(String text) {
  18. this.mText = text;
  19. }
  20. @Override
  21. public void translate(float dx, float dy) {
  22. mMatrix.postTranslate(dx, dy);
  23. }
  24. @Override
  25. public void scale(float scaleXRatio, float scaleYRatio, float scaleCenterX, float scaleCenterY) {
  26. mMatrix.postScale(scaleXRatio, scaleYRatio, scaleCenterX, scaleCenterY);
  27. }
  28. @Override
  29. public void draw(Canvas canvas) {
  30. if (mText != null && mPaint != null) {
  31. float matrix[] = new float[ 9];
  32. mMatrix.getValues(matrix);
  33. canvas.save();
  34. canvas.translate(matrix[ 2], matrix[ 5]);
  35. canvas.scale(matrix[ 0], matrix[ 4]);
  36. canvas.drawText(mText, 0, 0, mPaint);
  37. canvas.restore();
  38. //debug code:
  39. // Paint paint = new Paint();
  40. // paint.setStrokeWidth(5f);
  41. // paint.setColor(Color.BLUE);
  42. // paint.setStyle(Paint.Style.STROKE);
  43. // canvas.drawRect(getRange(), paint);
  44. }
  45. }
  46. @Override
  47. public RectF getRange() {
  48. //cjz: you can see this to know why I do that:https://www.jianshu.com/p/c83f59613c18
  49. if (mText != null && mPaint != null) {
  50. float matrix[] = new float[ 9];
  51. mMatrix.getValues(matrix);
  52. mRange = new RectF(
  53. matrix[ 2],
  54. matrix[ 5] - mPaint.getTextSize() * matrix[ 4],
  55. matrix[ 2] + (mText.length() * mPaint.getTextSize()) * matrix[ 0],
  56. matrix[ 5] + mPaint.getTextSize() / 2f * matrix[ 4]);
  57. return mRange;
  58. }
  59. return null;
  60. }
  61. @Override
  62. public void setPaint(Paint paint, Shader shader) {
  63. this.mPaint = new Paint(paint);
  64. if (shader != null) {
  65. this.mPaint.setShader(shader);
  66. }
  67. }
  68. @Override
  69. public PointF getScale() {
  70. float matrix[] = new float[ 9];
  71. mMatrix.getValues(matrix);
  72. return new PointF(matrix[ 0], matrix[ 4]);
  73. }
  74. @Override
  75. public PointF getXY() {
  76. float matrix[] = new float[ 9];
  77. mMatrix.getValues(matrix);
  78. return new PointF(matrix[ 2],
  79. matrix[ 5] - mPaint.getTextSize() * matrix[ 4]);
  80. }
  81. }

 

 

绘制View,通过遍历BaseShape并调用onDraw方法绘制图元,注意事件传递后调整图层层叠关系时,应该从顶(链表尾)到底(链表头)进行遍历,而绘制时则反之,才可以实现点击时,被点击的图元置顶的效果。另外刚刚设计的测量范围的方法在这里就可以派上用场了,可以用于确定是哪个图元被点击,就像UI SDK的设计:


  
  1. package com.example.android.camera2basic;
  2. import android.content.Context;
  3. import android.graphics.Bitmap;
  4. import android.graphics.BitmapFactory;
  5. import android.graphics.Canvas;
  6. import android.graphics.Color;
  7. import android.graphics.Paint;
  8. import android.graphics.RectF;
  9. import android.os.Build;
  10. import android.support.annotation.RequiresApi;
  11. import android.util.AttributeSet;
  12. import android.view.MotionEvent;
  13. import android.view.View;
  14. import com.chenjiezhu.waterMarkShape.BaseShape;
  15. import com.chenjiezhu.waterMarkShape.BitmapShape;
  16. import com.chenjiezhu.waterMarkShape.TextShape;
  17. import java.util.LinkedList;
  18. import java.util.List;
  19. public class WaterMarkView extends View {
  20. private Bitmap mBitmap;
  21. private List<BaseShape> mShapesList = new LinkedList<>();
  22. private BitmapShape mBitmapShape;
  23. private BaseShape mCurrentTouchShape;
  24. public WaterMarkView(Context context) {
  25. super(context);
  26. init();
  27. }
  28. public WaterMarkView(Context context, AttributeSet attrs) {
  29. super(context, attrs);
  30. init();
  31. }
  32. public WaterMarkView(Context context, AttributeSet attrs, int defStyleAttr) {
  33. super(context, attrs, defStyleAttr);
  34. init();
  35. }
  36. @RequiresApi(api = Build.VERSION_CODES.O)
  37. private void init() {
  38. mBitmap = BitmapFactory.decodeResource(getResources(), android.R.mipmap.sym_def_app_icon);
  39. for( int i = 0; i < 3; i++) {
  40. BitmapShape bs = new BitmapShape();
  41. bs.setmBitmap(mBitmap);
  42. bs.translate( 50 * i, 50 * i);
  43. mShapesList.add(bs);
  44. }
  45. TextShape textShape = new TextShape();
  46. Paint paint = new Paint();
  47. paint.setStrokeWidth( 5f);
  48. paint.setColor(Color.RED);
  49. paint.setStyle(Paint.Style.STROKE);
  50. paint.setTextSize( 150f);
  51. textShape.setPaint(paint, null);
  52. textShape.setText( "魅族大卖");
  53. textShape.translate( 200, 200);
  54. mShapesList.add(textShape);
  55. textShape = new TextShape();
  56. paint = new Paint();
  57. paint.setStrokeWidth( 5f);
  58. paint.setColor(Color.argb( 0.5f, 0.1f, 0.5f, 0.5f));
  59. paint.setStyle(Paint.Style.FILL_AND_STROKE);
  60. paint.setTextSize( 100f);
  61. textShape.setPaint(paint, null);
  62. textShape.setText( "水印编辑器Demo");
  63. textShape.translate( 400, 500);
  64. mShapesList.add(textShape);
  65. }
  66. @Override
  67. public boolean onTouchEvent(MotionEvent event) {
  68. switch (event.getAction()) {
  69. case MotionEvent.ACTION_DOWN: {
  70. for ( int i = mShapesList.size() - 1; i >= 0; i--) { //从顶传递到底
  71. BaseShape shape = mShapesList.get(i);
  72. RectF shapeRange = shape.getRange();
  73. if (shapeRange != null && shapeRange.contains(event.getX(), event.getY())) {
  74. mCurrentTouchShape = shape;
  75. //置顶选中图案
  76. mShapesList.remove(mCurrentTouchShape);
  77. mShapesList.add(mShapesList.size(), mCurrentTouchShape);
  78. mCurrentTouchShape.touchEvent(event);
  79. break;
  80. }
  81. }
  82. break;
  83. }
  84. case MotionEvent.ACTION_MOVE: {
  85. if (mCurrentTouchShape != null) {
  86. mCurrentTouchShape.touchEvent(event);
  87. break;
  88. }
  89. }
  90. case MotionEvent.ACTION_UP: {
  91. if (mCurrentTouchShape != null) {
  92. mCurrentTouchShape.touchEvent(event);
  93. mCurrentTouchShape = null;
  94. break;
  95. }
  96. }
  97. }
  98. invalidate();
  99. return true;
  100. }
  101. @Override
  102. protected void onDraw(Canvas canvas) {
  103. super.onDraw(canvas);
  104. for (BaseShape view : mShapesList) {
  105. view.draw(canvas);
  106. }
  107. }
  108. }

 

实际效果如下:

 

 


转载:https://blog.csdn.net/cjzjolly/article/details/106841082
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场