以一个着色游戏展开讲解Android中区域图像填色的方法

以一个着色游戏展开讲解Android中区域图像填色的方法,第1张

概述一、着色游戏概述近期群里偶然看到一哥们在群里聊不规则图像填充什么四联通、八联通什么的,就本身好学务实的态度去查阅了相关资料。对于这类着色的资料,最好的就是去搜索些相关app,根据我的观察呢,不规则图像填

一、着色游戏概述

近期群里偶然看到一哥们在群里聊不规则图像填充什么四联通、八联通什么的,就本身好学务实的态度去查阅了相关资料。对于这类着色的资料,最好的就是去搜索些相关app,根据我的观察呢,不规则图像填充在着色游戏里面应用居多,不过大致可以分为两种:

基于层的的填充 基于边界的填充

那么针对上述两种,我们会通过两篇博文来讲解,本篇就是叙述基于层的填充方式,那么什么基于层的填充方式呢?其实就是一张图实际上是由多个层组成的,每个层显示部分图像(无图像部分为透明),多层叠加后形成一张完整的图案,图层间是叠加的关系,类似下图。

相信大家如果学过PS,对上述肯定再了解不过了。比如你要绘制一个天空,你可以最底层去绘制蓝天,在上层绘制白云,再上层会执行小鸟。然后三层叠加以后就是一副小鸟在天空翱翔的图了。

二、效果与分析

好了,接下来看下今天的效果。

ok,可以看到一个简单的着色效果,其实原理很简单,首先呢,该图实际上是由7层组成:

例如下图。

那么如果我们需要给这幅图的某个位置着色,实际上是给某一层的非透明区域着色。实际上就转化为:

用户点击的(x,y)-> 判断落在哪一层的非透明区域 -> 然后给该层非透明区域着色。

ok,这样原理就叙述清楚了,实际上也是非常的简单,基于该原理,我们可以自定义一个VIEw,然后一幅一幅去绘制图层,最后按照上述步骤去编写代码。不过,我们还有可以偷懒的地方,其实没必要我们自己去一个图层一个图层的绘制,我们可以利用Drawable去完成图层叠加的工作,我们有一类Drawable叫做LayerDrawable,对应的xml为@R_198_3419@,我们可以通过使用LayerDrawable极大的简化我们的工作。

三、编码与实现

上述已经描述很清楚了,我再给大家细化一下:

@R_198_3419@中去定义我们的drawable
然后把该drawable作为我们VIEw的背景
复写ontouchEvent方法
判断用户点击的坐标落在哪一层的非透明位置,改变该层非透明区域颜色
(一)@R_198_3419@

 <?xml version="1.0" enCoding="utf-8"?><@R_198_3419@ xmlns:androID="http://schemas.androID.com/apk/res/androID"> <item  androID:drawable="@drawable/eel_mask1"/> <item  androID:drawable="@drawable/eel_mask2"/> <item  androID:drawable="@drawable/eel_mask3"/> <item  androID:drawable="@drawable/eel_mask4"/> <item  androID:drawable="@drawable/eel_mask5"/> <item  androID:drawable="@drawable/eel_mask6"/> <item  androID:drawable="@drawable/eel_mask7"/></@R_198_3419@>

ok,这样我们的drawable就ok了~~没撒说的,不过@R_198_3419@可以做很多事情,大家可以关注下。

(二)VIEw代码

package com.zhy.colour_app_01;import androID.content.Context;import androID.graphics.Bitmap;import androID.graphics.color;import androID.graphics.PorterDuff;import androID.graphics.drawable.BitmapDrawable;import androID.graphics.drawable.Drawable;import androID.graphics.drawable.LayerDrawable;import androID.util.AttributeSet;import androID.util.Log;import androID.vIEw.MotionEvent;import androID.vIEw.VIEw;import java.util.Random;/** * Created by zhy on 15/5/14. */public class ColourImageBaseLayerVIEw extends VIEw{ private LayerDrawable mDrawables; public ColourImageBaseLayerVIEw(Context context,AttributeSet attrs) {  super(context,attrs);  mDrawables = (LayerDrawable) getBackground(); } @OverrIDe protected voID onMeasure(int wIDthMeasureSpec,int heightmeasureSpec) {  setMeasuredDimension(mDrawables.getIntrinsicWIDth(),mDrawables.getIntrinsicHeight()); } @OverrIDe public boolean ontouchEvent(MotionEvent event) {  final float x = event.getX();  final float y = event.getY();  if (event.getAction() == MotionEvent.ACTION_DOWN)  {   Drawable drawable = findDrawable(x,y);   if (drawable != null)    drawable.setcolorFilter(randomcolor(),PorterDuff.Mode.SRC_IN);  }  return super.ontouchEvent(event); } private int randomcolor() {  Random random = new Random();  int color = color.argb(255,random.nextInt(256),random.nextInt(256));  return color; } private Drawable findDrawable(float x,float y) {  final int numberOfLayers = mDrawables.getNumberOfLayers();  Drawable drawable = null;  Bitmap bitmap = null;  for (int i = numberOfLayers - 1; i >= 0; i--)  {   drawable = mDrawables.getDrawable(i);   bitmap = ((BitmapDrawable) drawable).getBitmap();   try   {    int pixel = bitmap.getPixel((int) x,(int) y);    if (pixel == color.transparent)    {     continue;    }   } catch (Exception e)   {    continue;   }   return drawable;  }  return null; }}

ok,代码也比较简单,首先我们把drawable作为vIEw的背景,然后在构造中获取drawable(LayerDrawable)。接下来复写ontouchEvent,捕获用户点击的(x,y),根据(x,y)去找出当前点击的是哪一层(必须点击在非透明区域),最后通过设置setcolorFilter去改变颜色即可~很easy吧最后贴下布局文件:

(三)布局文件

<relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"    xmlns:tools="http://schemas.androID.com/tools"    androID:layout_wIDth="match_parent"    androID:layout_height="match_parent"    androID:paddingleft="@dimen/activity_horizontal_margin"    androID:paddingRight="@dimen/activity_horizontal_margin"    androID:paddingtop="@dimen/activity_vertical_margin"    androID:paddingBottom="@dimen/activity_vertical_margin"    tools:context=".MainActivity"> <com.zhy.colour_app_01.ColourImageBaseLayerVIEw  androID:background="@drawable/eel"  androID:layout_wIDth="match_parent"  androID:layout_centerInParent="true"  androID:layout_height="match_parent"/></relativeLayout>

四、边界的填充
1.图像的填充有2种经典算法。

一种是种子填充法。种子填充法理论上能够填充任意区域和图形,但是这种算法存在大量的反复入栈和大规模的递归,降低了填充效率。
另一种是扫描线填充法。
注意:实际上图像填充的算法还是很多的,有兴趣可以去Google学术上去搜一搜。
ok,下面先看看效果图:

ok,可以看到这样的颜色填充比上一篇的基于层的在素材的准备上要easy 很多~~~

2.原理分析

首先我们简述下原理,我们在点击的时候拿到点击点的”颜色”,然后按照我们选择的算法进行填色即可。

算法1:种子填充法,四联通/八联通
算法简介:假设要将某个区域填充成红色。

从用户点击点的像素开始,上下左右(八联通还有左上,左下,右上,右下)去判断颜色,如果四个方向上的颜色与当前点击点的像素一致,则改变颜色至目标色。然后继续上述这个过程。

ok,可以看到这是一个递归的过程,1个点到4个,4个到16个不断的去延伸。如果按照这种算法,你会写出类似这样的代码:

/**  * @param pixels 像素数组  * @param w  宽度  * @param h  高度  * @param pixel 当前点的颜色  * @param newcolor 填充色  * @param i  横坐标  * @param j  纵坐标  */ private voID fillcolor01(int[] pixels,int w,int h,int pixel,int newcolor,int i,int j) {  int index = j * w + i;  if (pixels[index] != pixel || i >= w || i < 0 || j < 0 || j >= h)   return;  pixels[index] = newcolor;  //上  fillcolor01(pixels,w,h,pixel,newcolor,i,j - 1);  //右  fillcolor01(pixels,i + 1,j);  //下  fillcolor01(pixels,j + 1);  //左  fillcolor01(pixels,i - 1,j); }

代码很简单,但是如果你去运行,会发生StackOverflowException异常,这个异常主要是因为大量的递归造成的。虽然简单,但是在移动设备上使用该方法不行。

于是,我就想,这个方法不是递归深度过多么,那么我可以使用一个Stack去存像素点,减少递归的深度和次数,于是我把代码改成如下的方式:

/**  * @param pixels 像素数组  * @param w  宽度  * @param h  高度  * @param pixel 当前点的颜色  * @param newcolor 填充色  * @param i  横坐标  * @param j  纵坐标  */ private voID fillcolor(int[] pixels,int j) {  mStacks.push(new Point(i,j));  while (!mStacks.isEmpty())  {   Point seed = mStacks.pop();   Log.e("TAG","seed = " + seed.x + ",seed = " + seed.y);   int index = seed.y * w + seed.x;   pixels[index] = newcolor;   if (seed.y > 0)   {    int top = index - w;    if (pixels[top] == pixel)    {     mStacks.push(new Point(seed.x,seed.y - 1));    }   }   if (seed.y < h - 1)   {    int bottom = index + w;    if (pixels[bottom] == pixel)    {     mStacks.push(new Point(seed.x,seed.y + 1));    }   }   if (seed.x > 0)   {    int left = index - 1;    if (pixels[left] == pixel)    {     mStacks.push(new Point(seed.x - 1,seed.y));    }   }   if (seed.x < w - 1)   {    int right = index + 1;    if (pixels[right] == pixel)    {     mStacks.push(new Point(seed.x + 1,seed.y));    }   }  } }

方法的思想也比较简单,将当前像素点入栈,然后出栈着色,接下来分别判断四个方向的,如果符合条件也进行入栈(只要栈不为空持续运行)。ok,这个方法我也尝试跑了下,恩,这次不会报错了,但是速度特别的慢~~~~慢得我是不可接受的。(有兴趣可以尝试,记得如果ANR,点击等待)。

这样来看,第一种算法,我们是不考虑了,没有办法使用,主要原因是假设对于矩形同色区域,都是需要填充的,而算法一依然是各种入栈。于是考虑第二种算法

扫描线填充法

详细可参考 扫描线种子填充算法的解析和扫描线种子填充算法。
算法思想:

初始化一个空的栈用于存放种子点,将种子点(x,y)入栈;
判断栈是否为空,如果栈为空则结束算法,否则取出栈顶元素作为当前扫描线的种子点(x,y),y是当前的扫描线;
从种子点(x,y)出发,沿当前扫描线向左、右两个方向填充,直到边界。分别标记区段的左、右端点坐标为xleft和xRight;
分别检查与当前扫描线相邻的y - 1和y + 1两条扫描线在区间[xleft,xRight]中的像素,从xRight开始向xleft方向搜索,假设扫描的区间为AAABAAC(A为种子点颜色),那么将B和C前面的A作为种子点压入栈中,然后返回第(2)步;
上述参考自参考文献[4],做了些修改,文章[4]中描述算法,测试有一点问题,所以做了修改.

可以看到该算法,基本上是一行一行着色的,这样的话在大块需要着色区域的效率比算法一要高很多。

ok,关于算法的步骤大家目前觉得模糊,一会可以参照我们的代码。选定了算法以后,接下来就开始编码了。

3.编码实现

我们代码中引入了一个边界颜色,如果设置的话,着色的边界参考为该边界颜色,否则会只要与种子颜色不一致为边界。

(一)构造方法与测量

public class ColourImageVIEw extends ImageVIEw{ private Bitmap mBitmap; /**  * 边界的颜色  */ private int mbordercolor = -1; private boolean hasbordercolor = false; private Stack<Point> mStacks = new Stack<Point>(); public ColourImageVIEw(Context context,attrs);  TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.ColourImageVIEw);  mbordercolor = ta.getcolor(R.styleable.ColourImageVIEw_border_color,-1);  hasbordercolor = (mbordercolor != -1);  L.e("hasbordercolor = " + hasbordercolor + ",mbordercolor = " + mbordercolor);  ta.recycle(); } @OverrIDe protected voID onMeasure(int wIDthMeasureSpec,int heightmeasureSpec) {  super.onMeasure(wIDthMeasureSpec,heightmeasureSpec);  int vIEwWIDth = getMeasureDWIDth();  int vIEwHeight = getMeasuredHeight();  //以宽度为标准,等比例缩放vIEw的高度  setMeasuredDimension(vIEwWIDth,getDrawable().getIntrinsicHeight() * vIEwWIDth / getDrawable().getIntrinsicWIDth());  L.e("vIEw's wIDth = " + getMeasureDWIDth() + ",vIEw's height = " + getMeasuredHeight());  //根据drawable,去得到一个和vIEw一样大小的bitmap  BitmapDrawable drawable = (BitmapDrawable) getDrawable();  Bitmap bm = drawable.getBitmap();  mBitmap = Bitmap.createScaledBitmap(bm,getMeasureDWIDth(),getMeasuredHeight(),false); }

可以看到我们选择的是继承ImageVIEw,这样只需要将图片设为src即可。
构造方法中获取我们的自定义边界颜色,当然可以不设置~~
重写测量的目的是为了获取一个和VIEw一样大小的Bitmap便于我们 *** 作。

接下来就是点击啦~

4.ontouchEvent

@OverrIDe public boolean ontouchEvent(MotionEvent event) {  final int x = (int) event.getX();  final int y = (int) event.getY();  if (event.getAction() == MotionEvent.ACTION_DOWN)  {   //填色   fillcolorToSameArea(x,y);  }  return super.ontouchEvent(event); } /**  * 根据x,y获得改点颜色,进行填充  *  * @param x  * @param y  */ private voID fillcolorToSameArea(int x,int y) {  Bitmap bm = mBitmap;  int pixel = bm.getPixel(x,y);  if (pixel == color.transparent || (hasbordercolor && mbordercolor == pixel))  {   return;  }  int newcolor = randomcolor();  int w = bm.getWIDth();  int h = bm.getHeight();  //拿到该bitmap的颜色数组  int[] pixels = new int[w * h];  bm.getPixels(pixels,h);  //填色  fillcolor(pixels,x,y);  //重新设置bitmap  bm.setPixels(pixels,h);  setimageDrawable(new BitmapDrawable(bm)); }

可以看到,我们在ontouchEvent中获取(x,y),然后拿到改点坐标:

获得点击点颜色,获得整个bitmap的像素数组
改变这个数组中的颜色
然后重新设置给bitmap,重新设置给ImageVIEw
重点就是通过fillcolor去改变数组中的颜色

/**  * @param pixels 像素数组  * @param w  宽度  * @param h  高度  * @param pixel 当前点的颜色  * @param newcolor 填充色  * @param i  横坐标  * @param j  纵坐标  */ private voID fillcolor(int[] pixels,int j) {  //步骤1:将种子点(x,y)入栈;  mStacks.push(new Point(i,j));  //步骤2:判断栈是否为空,  // 如果栈为空则结束算法,否则取出栈顶元素作为当前扫描线的种子点(x,y),  // y是当前的扫描线;  while (!mStacks.isEmpty())  {   /**    * 步骤3:从种子点(x,y)出发,沿当前扫描线向左、右两个方向填充,    * 直到边界。分别标记区段的左、右端点坐标为xleft和xRight;    */   Point seed = mStacks.pop();   //L.e("seed = " + seed.x + ",seed = " + seed.y);   int count = filllineleft(pixels,seed.x,seed.y);   int left = seed.x - count + 1;   count = filllineRight(pixels,seed.x + 1,seed.y);   int right = seed.x + count;   /**    * 步骤4:    * 分别检查与当前扫描线相邻的y - 1和y + 1两条扫描线在区间[xleft,xRight]中的像素,    * 从xRight开始向xleft方向搜索,假设扫描的区间为AAABAAC(A为种子点颜色),    * 那么将B和C前面的A作为种子点压入栈中,然后返回第(2)步;    */   //从y-1找种子   if (seed.y - 1 >= 0)    findSeedInNewline(pixels,seed.y - 1,left,right);   //从y+1找种子   if (seed.y + 1 < h)    findSeedInNewline(pixels,seed.y + 1,right);  } }


可以看到我已经很清楚的将该算法的四个步骤标识到该方法中。好了,最后就是一些依赖的细节上的方法

 /**  * 在新行找种子节点  *  * @param pixels  * @param pixel  * @param w  * @param h  * @param i  * @param left  * @param right  */ private voID findSeedInNewline(int[] pixels,int left,int right) {  /**   * 获得该行的开始索引   */  int begin = i * w + left;  /**   * 获得该行的结束索引   */  int end = i * w + right;  boolean hasSeed = false;  int rx = -1,ry = -1;  ry = i;  /**   * 从end到begin,找到种子节点入栈(AAABAAAB,则B前的A为种子节点)   */  while (end >= begin)  {   if (pixels[end] == pixel)   {    if (!hasSeed)    {     rx = end % w;     mStacks.push(new Point(rx,ry));     hasSeed = true;    }   } else   {    hasSeed = false;   }   end--;  } } /**  * 往右填色,返回填充的个数  *  * @return  */ private int filllineRight(int[] pixels,int x,int y) {  int count = 0;  while (x < w)  {   //拿到索引   int index = y * w + x;   if (needFillPixel(pixels,index))   {    pixels[index] = newcolor;    count++;    x++;   } else   {    break;   }  }  return count; } /**  * 往左填色,返回填色的数量值  *  * @return  */ private int filllineleft(int[] pixels,int y) {  int count = 0;  while (x >= 0)  {   //计算出索引   int index = y * w + x;   if (needFillPixel(pixels,index))   {    pixels[index] = newcolor;    count++;    x--;   } else   {    break;   }  }  return count; } private boolean needFillPixel(int[] pixels,int index) {  if (hasbordercolor)  {   return pixels[index] != mbordercolor;  } else  {   return pixels[index] == pixel;  } } /**  * 返回一个随机颜色  *  * @return  */ private int randomcolor() {  Random random = new Random();  int color = color.argb(255,random.nextInt(256));  return color; }

ok,到此,代码就介绍完毕了~~~

最后贴下布局文件~~

<relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"    xmlns:tools="http://schemas.androID.com/tools"    xmlns:zhy="http://schemas.androID.com/apk/res-auto"    androID:layout_wIDth="match_parent"    androID:layout_height="match_parent"    androID:paddingleft="@dimen/activity_horizontal_margin"    androID:paddingRight="@dimen/activity_horizontal_margin"    androID:paddingtop="@dimen/activity_vertical_margin"    androID:paddingBottom="@dimen/activity_vertical_margin"    tools:context=".MainActivity"> <com.zhy.colour_app_01.ColourImageVIEw  zhy:border_color="#FF000000"  androID:src="@drawable/image_007"  androID:background="#33ff0000"  androID:layout_wIDth="match_parent"  androID:layout_centerInParent="true"  androID:layout_height="match_parent"/></relativeLayout><?xml version="1.0" enCoding="utf-8"?><resources> <declare-styleable name="ColourImageVIEw">  <attr name="border_color" format="color|reference"></attr> </declare-styleable></resources>

总结

以上是内存溢出为你收集整理的以一个着色游戏展开讲解Android中区域图像填色的方法全部内容,希望文章能够帮你解决以一个着色游戏展开讲解Android中区域图像填色的方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1149615.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存