当前位置: 移动技术网 > IT编程>开发语言>c# > Unity绘制二维动态曲线

Unity绘制二维动态曲线

2019年07月18日  | 移动技术网IT编程  | 我要评论

一、前言

之前用line render实现过这个动态曲线的绘制,使用这个实在太不方便了,一直寻思怎么在一张图片上通过控制图片的像素值实现曲线的动态绘制。参考了unity的官网教程实现了这个,效果图如图所示:

这样实现的效果比linerender 要好,并且不怎么消耗计算和渲染

二、实现

1、代码创建一个背景贴图,并将这个贴图给ugui的rawimage控件

//创建背景贴图
  widthpixels = (int)(screen.width * width);
  heightpixels = (int)(screen.height * height);
  bgtexture = new texture2d(widthpixels, heightpixels);
 
  bgimage.texture = bgtexture;
  bgimage.setnativesize();

2、计算曲线数据列表对应贴图中的像素索引

int i;
  int j;
 
  if (mathf.abs(to.x - from.x) > mathf.abs(to.y - from.y))
  {
   // horizontal line.
   i = 0;
   j = 1;
  }
  else
  {
   // vertical line.
   i = 1;
   j = 0;
  }
 
  int x = (int)from[i];
  int delta = (int)mathf.sign(to[i] - from[i]);
  while (x != (int)to[i])
  {
   int y = (int)mathf.round(from[j] + (x - from[i]) * (to[j] - from[j]) / (to[i] - from[i]));
 
   int index;
   if (i == 0)
    index = y * widthpixels + x;
   else
    index = x * widthpixels + y;
 
   index = mathf.clamp(index, 0, pixelsdrawline.length - 1);
   pixelsdrawline[index] = color;
 
   x += delta;
  }

3、在update里实时更新贴图的像素值

array.copy(pixelsbg, pixelsdrawline, pixelsbg.length);
 
  // 基准线
  drawline(new vector2(0f, heightpixels * 0.5f), new vector2(widthpixels, heightpixels * 0.5f), zerocolor);
 
  for (int i = 0; i < listpoints.count-1; i++)
  {
   vector2 from = listpoints[i];
   vector2 to = listpoints[i + 1];
   drawline(from, to, colorline1);
  }
 
  bgtexture.setpixels32(pixelsdrawline);
  bgtexture.apply();

三、总结

1、比使用line render要节省计算和渲染

2、真正实现了二维的曲线绘制,line render始终是3维的

3、曲线坐标的x和y的值不能超过贴图的宽度和高度,否则不能绘制

4、完整的工程下载地址:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网