[关闭]
@coder-pig 2015-10-16T12:51:01.000000Z 字数 9155 阅读 2432

Android基础入门教程——8.3.2 绘图类实战示例

Android基础入门教程


本节引言:

前两节我们学了Bitmap和一些基本的绘图API的属性以及常用的方法,但心里总觉得有点
不踏实,总得写点什么加深下映像是吧,嗯,本节我们就来写两个简单的例子:
1.简单画图板的实现
2.帮美女擦衣服的简单实现
嘿嘿,第二个例子是小猪刚学安卓写的一个小Demo~嘿嘿~
开始本节内容~


1.实战示例1:简单画图板的实现:

这个相信大家都不陌生,很多手机都会自带一个给用户涂鸦的画图板,这里我们就来写个简单的
例子,首先我们分析下,实现这个东东的一些逻辑:
Q1:这个画板放在哪里?
答:View里,我们自定义一个View,在onDraw()里完成绘制,另外View还有个onTouchEvent的方法,
我们可以在获取用户的手势操作!
q2.需要准备些什么?
答:一只画笔(Paint),一块画布(Canvas),一个路径(Path)记录用户绘制路线;
另外划线的时候,每次都是从上次拖动时间的发生点到本次拖动时间的发生点!那么之前绘制的
就会丢失,为了保存之前绘制的内容,我们可以引入所谓的“双缓冲”技术:
其实就是每次不是直接绘制到Canvas上,而是先绘制到Bitmap上,等Bitmap上的绘制完了,
再一次性地绘制到View上而已!
3.具体的实现流程?
答:初始化画笔,设置颜色等等一些参数;在View的onMeasure()方法中创建一个View大小的Bitmap,
同时创建一个Canvas;onTouchEvent中获得X,Y坐标,做绘制连线,最后invalidate()重绘,即调用
onDraw方法将bitmap的东东画到Canvas上!

好了,逻辑知道了,下面就上代码了:
MyView.java

  1. /**
  2. * Created by Jay on 2015/10/15 0015.
  3. */
  4. public class MyView extends View{
  5. private Paint mPaint; //绘制线条的Path
  6. private Path mPath; //记录用户绘制的Path
  7. private Canvas mCanvas; //内存中创建的Canvas
  8. private Bitmap mBitmap; //缓存绘制的内容
  9. private int mLastX;
  10. private int mLastY;
  11. public MyView(Context context) {
  12. super(context);
  13. init();
  14. }
  15. public MyView(Context context, AttributeSet attrs) {
  16. super(context, attrs);
  17. init();
  18. }
  19. public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
  20. super(context, attrs, defStyleAttr);
  21. init();
  22. }
  23. private void init(){
  24. mPath = new Path();
  25. mPaint = new Paint(); //初始化画笔
  26. mPaint.setColor(Color.GREEN);
  27. mPaint.setAntiAlias(true);
  28. mPaint.setDither(true);
  29. mPaint.setStyle(Paint.Style.STROKE);
  30. mPaint.setStrokeJoin(Paint.Join.ROUND); //结合处为圆角
  31. mPaint.setStrokeCap(Paint.Cap.ROUND); // 设置转弯处为圆角
  32. mPaint.setStrokeWidth(20); // 设置画笔宽度
  33. }
  34. @Override
  35. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  36. super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  37. int width = getMeasuredWidth();
  38. int height = getMeasuredHeight();
  39. // 初始化bitmap,Canvas
  40. mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
  41. mCanvas = new Canvas(mBitmap);
  42. }
  43. //重写该方法,在这里绘图
  44. @Override
  45. protected void onDraw(Canvas canvas) {
  46. drawPath();
  47. canvas.drawBitmap(mBitmap, 0, 0, null);
  48. }
  49. //绘制线条
  50. private void drawPath(){
  51. mCanvas.drawPath(mPath, mPaint);
  52. }
  53. @Override
  54. public boolean onTouchEvent(MotionEvent event) {
  55. int action = event.getAction();
  56. int x = (int) event.getX();
  57. int y = (int) event.getY();
  58. switch (action)
  59. {
  60. case MotionEvent.ACTION_DOWN:
  61. mLastX = x;
  62. mLastY = y;
  63. mPath.moveTo(mLastX, mLastY);
  64. break;
  65. case MotionEvent.ACTION_MOVE:
  66. int dx = Math.abs(x - mLastX);
  67. int dy = Math.abs(y - mLastY);
  68. if (dx > 3 || dy > 3)
  69. mPath.lineTo(x, y);
  70. mLastX = x;
  71. mLastY = y;
  72. break;
  73. }
  74. invalidate();
  75. return true;
  76. }
  77. }

运行效果图

你可以根据自己的需求进行扩展,比如加上修改画笔大小,修改画笔颜色,保存自己画的图等!
发散思维,自己动手~


2.实战示例2:擦掉美女衣服的实现

核心思路是:
利用帧布局,前后两个ImageView,前面的显示未擦掉衣服的情况,后面的显示擦掉衣服后的情况!
为两个ImageView设置美女图片后,接着为前面的ImageView设置OnTouchListener!在这里对手指
触碰点附近的20*20个像素点,设置为透明!

运行效果图

代码实现

Step 1:第一个选妹子的Activity相关的编写,首先是界面,一个ImageView,Button和Gallery!

activity_main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical">
  6. <ImageView
  7. android:id="@+id/img_choose"
  8. android:layout_width="320dp"
  9. android:layout_height="320dp" />
  10. <Button
  11. android:id="@+id/btn_choose"
  12. android:layout_width="wrap_content"
  13. android:layout_height="wrap_content"
  14. android:text="脱光她!" />
  15. <Gallery
  16. android:id="@+id/gay_choose"
  17. android:layout_width="match_parent"
  18. android:layout_height="wrap_content"
  19. android:layout_marginTop="25dp"
  20. android:spacing="1pt"
  21. android:unselectedAlpha="0.6" />
  22. </LinearLayout>

接着是我们Gallery的Adapter类,这里我们重写下BaseAdapter,而里面就显示一个图片比较简单,
就不另外写一个布局了!

MeiziAdapter.java:

  1. /**
  2. * Created by Jay on 2015/10/16 0016.
  3. */
  4. public class MeiziAdapter extends BaseAdapter{
  5. private Context mContext;
  6. private int[] mData;
  7. public MeiziAdapter() {
  8. }
  9. public MeiziAdapter(Context mContext,int[] mData) {
  10. this.mContext = mContext;
  11. this.mData = mData;
  12. }
  13. @Override
  14. public int getCount() {
  15. return mData.length;
  16. }
  17. @Override
  18. public Object getItem(int position) {
  19. return mData[position];
  20. }
  21. @Override
  22. public long getItemId(int position) {
  23. return position;
  24. }
  25. @Override
  26. public View getView(int position, View convertView, ViewGroup parent) {
  27. ImageView imgMezi = new ImageView(mContext);
  28. imgMezi.setImageResource(mData[position]); //创建一个ImageView
  29. imgMezi.setScaleType(ImageView.ScaleType.FIT_XY); //设置imgView的缩放类型
  30. imgMezi.setLayoutParams(new Gallery.LayoutParams(250, 250)); //为imgView设置布局参数
  31. TypedArray typedArray = mContext.obtainStyledAttributes(R.styleable.Gallery);
  32. imgMezi.setBackgroundResource(typedArray.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0));
  33. return imgMezi;
  34. }
  35. }

最后到我们的Activity,也很简单,无非是为gallery设置onSelected事件,点击按钮后把,当前选中的
Position传递给下一个页面!

MainActivity.java

  1. public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener,
  2. View.OnClickListener {
  3. private Context mContext;
  4. private ImageView img_choose;
  5. private Button btn_choose;
  6. private Gallery gay_choose;
  7. private int index = 0;
  8. private MeiziAdapter mAdapter = null;
  9. private int[] imageIds = new int[]
  10. {
  11. R.mipmap.pre1, R.mipmap.pre2, R.mipmap.pre3, R.mipmap.pre4,
  12. R.mipmap.pre5, R.mipmap.pre6, R.mipmap.pre7, R.mipmap.pre8,
  13. R.mipmap.pre9, R.mipmap.pre10, R.mipmap.pre11, R.mipmap.pre12,
  14. R.mipmap.pre13, R.mipmap.pre14, R.mipmap.pre15, R.mipmap.pre16,
  15. R.mipmap.pre17, R.mipmap.pre18, R.mipmap.pre19, R.mipmap.pre20,
  16. R.mipmap.pre21
  17. };
  18. @Override
  19. protected void onCreate(Bundle savedInstanceState) {
  20. super.onCreate(savedInstanceState);
  21. setContentView(R.layout.activity_main);
  22. mContext = MainActivity.this;
  23. bindViews();
  24. }
  25. private void bindViews() {
  26. img_choose = (ImageView) findViewById(R.id.img_choose);
  27. btn_choose = (Button) findViewById(R.id.btn_choose);
  28. gay_choose = (Gallery) findViewById(R.id.gay_choose);
  29. mAdapter = new MeiziAdapter(mContext, imageIds);
  30. gay_choose.setAdapter(mAdapter);
  31. gay_choose.setOnItemSelectedListener(this);
  32. btn_choose.setOnClickListener(this);
  33. }
  34. @Override
  35. public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
  36. img_choose.setImageResource(imageIds[position]);
  37. index = position;
  38. }
  39. @Override
  40. public void onNothingSelected(AdapterView<?> parent) {
  41. }
  42. @Override
  43. public void onClick(View v) {
  44. Intent it = new Intent(mContext,CaClothes.class);
  45. Bundle bundle = new Bundle();
  46. bundle.putCharSequence("num", Integer.toString(index));
  47. it.putExtras(bundle);
  48. startActivity(it);
  49. }
  50. }

接着是我们擦掉妹子衣服的页面了,布局比较简单,FrameLayout + 前后两个ImageView:

activity_caclothes.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent">
  5. <ImageView
  6. android:id="@+id/img_after"
  7. android:layout_width="wrap_content"
  8. android:layout_height="wrap_content" />
  9. <ImageView
  10. android:id="@+id/img_before"
  11. android:layout_width="wrap_content"
  12. android:layout_height="wrap_content" />
  13. </FrameLayout>

接着到就到Java部分的代码了:

CaClothes.java

  1. /**
  2. * Created by Jay on 2015/10/16 0016.
  3. */
  4. public class CaClothes extends AppCompatActivity implements View.OnTouchListener {
  5. private ImageView img_after;
  6. private ImageView img_before;
  7. private Bitmap alterBitmap;
  8. private Canvas canvas;
  9. private Paint paint;
  10. private Bitmap after;
  11. private Bitmap before;
  12. private int position;
  13. int[] imageIds1 = new int[]
  14. {
  15. R.mipmap.pre1, R.mipmap.pre2, R.mipmap.pre3, R.mipmap.pre4,
  16. R.mipmap.pre5, R.mipmap.pre6, R.mipmap.pre7, R.mipmap.pre8,
  17. R.mipmap.pre9, R.mipmap.pre10, R.mipmap.pre11, R.mipmap.pre12,
  18. R.mipmap.pre13, R.mipmap.pre14, R.mipmap.pre15, R.mipmap.pre16,
  19. R.mipmap.pre17, R.mipmap.pre18, R.mipmap.pre19, R.mipmap.pre20,
  20. R.mipmap.pre21
  21. };
  22. int[] imageIds2 = new int[]
  23. {
  24. R.mipmap.after1, R.mipmap.after2, R.mipmap.after3, R.mipmap.after4,
  25. R.mipmap.after5, R.mipmap.after6, R.mipmap.after7, R.mipmap.after8,
  26. R.mipmap.after9, R.mipmap.after10, R.mipmap.after11, R.mipmap.after12,
  27. R.mipmap.after13, R.mipmap.after14, R.mipmap.after15, R.mipmap.after16,
  28. R.mipmap.after17, R.mipmap.after18, R.mipmap.after19, R.mipmap.after20,
  29. R.mipmap.after21
  30. };
  31. @Override
  32. public void onCreate(Bundle savedInstanceState) {
  33. super.onCreate(savedInstanceState);
  34. setContentView(R.layout.activity_caclothes);
  35. Bundle bd = getIntent().getExtras();
  36. position = Integer.parseInt(bd.getString("num"));
  37. bindViews();
  38. }
  39. private void bindViews() {
  40. img_after = (ImageView) findViewById(R.id.img_after);
  41. img_before = (ImageView) findViewById(R.id.img_before);
  42. BitmapFactory.Options opts = new BitmapFactory.Options();
  43. opts.inSampleSize = 1;
  44. after = BitmapFactory.decodeResource(getResources(), imageIds2[position], opts);
  45. before = BitmapFactory.decodeResource(getResources(), imageIds1[position], opts);
  46. //定义出来的是只读图片
  47. alterBitmap = Bitmap.createBitmap(before.getWidth(), before.getHeight(), Bitmap.Config.ARGB_4444);
  48. canvas = new Canvas(alterBitmap);
  49. paint = new Paint();
  50. paint.setStrokeCap(Paint.Cap.ROUND);
  51. paint.setStrokeJoin(Paint.Join.ROUND);
  52. paint.setStrokeWidth(5);
  53. paint.setColor(Color.BLACK);
  54. paint.setAntiAlias(true);
  55. canvas.drawBitmap(before, new Matrix(), paint);
  56. img_after.setImageBitmap(after);
  57. img_before.setImageBitmap(before);
  58. img_before.setOnTouchListener(this);
  59. }
  60. @Override
  61. public boolean onTouch(View v, MotionEvent event) {
  62. switch (event.getAction()) {
  63. case MotionEvent.ACTION_DOWN:
  64. break;
  65. case MotionEvent.ACTION_MOVE:
  66. int newX = (int) event.getX();
  67. int newY = (int) event.getY();
  68. //setPixel方法是将某一个像素点设置成一个颜色,而这里我们把他设置成透明
  69. //另外通过嵌套for循环将手指触摸区域的20*20个像素点设置为透明
  70. for (int i = -20; i < 20; i++) {
  71. for (int j = -20; j < 20; j++) {
  72. if (i + newX >= 0 && j + newY >= 0 && i + newX < before.getWidth() && j + newY < before.getHeight())
  73. alterBitmap.setPixel(i + newX, j + newY, Color.TRANSPARENT);
  74. }
  75. }
  76. img_before.setImageBitmap(alterBitmap);
  77. break;
  78. }
  79. return true;
  80. }
  81. }

代码也不算苦涩难懂,还是比较简单的哈,嗯,效果图看看就好,别做那么多右手螺旋定则哈....


3.代码示例下载:

DrawDemo1.zip 项目比较大,20多M,图片资源比较多,你懂的~


本节小结:

好的,本节写了关于绘图的两个小例子,还是蛮有趣的,相信你发下了,擦美女衣服那里,
消除的时候是方块的,不那么完美是吧,没事,下节我们学多个PorterDuff这个东西,我们
再来写多个例子,相比起这个代码就简单很多了,另外,时间关系,代码并没有去优化
或者整理,可以根据自己需求进行修改~好的,就说这么多,祝大家周末愉快~

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注