关于ReactNative绘图,你应该知道的东西

最近要Rn的项目要使用到绘图,但是网上关于Rn绘图的文章还是比较少 而且讲的不全,所以只好自己研究一下了。

react native中的绘图api在art包中,先看看art包中都有哪些东西:

var ReactART = {
  LinearGradient: LinearGradient,
  RadialGradient: RadialGradient,
  Pattern: Pattern,
  Transform: Transform,
  Path: Path,
  Surface: Surface,
  Group: Group,
  ClippingRectangle: ClippingRectangle,
  Shape: Shape,
  Text: Text,
};

ReactNativeART.js导出的对象,也是我们绘图中可以使用的组件

art包的基本使用

Surface:
相当于画板组件,其他的组件要包括在Surface中: 例如

 <Surface width="300" height="300">
 <Shape d={pathCircle}  stroke="#000000" strokeWidth={1}/>
 </Surface>

下面的代码截取可能会没有Surface,要注意区分

Path:

表示一个绘制路径 基本上和java中的path是一样的

用画圆弧举个栗子:

arc: function(x, y, rx, ry, outer, counterClockwise, rotation){
   return this.arcTo(this.penX + (+x), this.penY + (+y), rx, ry, outer, counterClockwise, rotation);
},

arc和arcTo的区别是arc使用的是相对坐标 arcTo使用的是绝对坐标

x y 终点的位置 起点就是path的当前点
rx ry x轴 y轴的半径
outer:不知道是什么鬼 外接矩形?
counterClockwise: 逆时针 true/fase
rotation:旋转角度

let pathCircle= new Path()
    .moveTo(50,50)
    .arc(0,99,25,25,true,false)
    .close();

表示终点的坐标相对于起点是x=0 y=99 半径是25 顺时针绘制

Shape:

shape主要负责path的绘制

 <Shape d={pathCircle}  stroke="#000000" strokeWidth={1}/>

shape中可以使用的属性如下:

class Shape extends React.Component {
  render() {
    var props = this.props;
    var path = props.d || childrenAsString(props.children);
    var d = new Path(path).toJSON();
    return (
      <NativeShape
        fill={extractBrush(props.fill, props)}
        opacity={extractOpacity(props)}
        stroke={extractColor(props.stroke)}
        strokeCap={extractStrokeCap(props.strokeCap)}
        strokeDash={props.strokeDash || null}
        strokeJoin={extractStrokeJoin(props.strokeJoin)}
        strokeWidth={extractNumber(props.strokeWidth, 1)}
        transform={extractTransform(props)}

        d={d}
      />
    );
  }
}

fill:填充的颜色
stroke:线条颜色
strokeCap 线条端点的形状:

function extractStrokeCap(strokeCap) {
  switch (strokeCap) {
    case 'butt': return 0;
    case 'square': return 2;
    default: return 1; // round
  }
}

有三个值可以用 butt square round 默认是round

strokeDash:虚线绘制 ;[10,5] 表示画10长度的实线 5长度的空白
strokeJoin:线条连接处的形状

function extractStrokeJoin(strokeJoin) {
  switch (strokeJoin) {
    case 'miter': return 0;
    case 'bevel': return 2;
    default: return 1; // round
  }
}

有三个值可以选

d:要绘制的path

Transform:
变换
具体的属性如下

function extractTransform(props) {

//x y的缩放
  var scaleX = props.scaleX != null ? props.scaleX :
               props.scale != null ? props.scale : 1;
  var scaleY = props.scaleY != null ? props.scaleY :
               props.scale != null ? props.scale : 1;
//移动  旋转 缩放等
  pooledTransform
    .transformTo(1, 0, 0, 1, 0, 0)
    .move(props.x || 0, props.y || 0)
    .rotate(props.rotation || 0, props.originX, props.originY)
    .scale(scaleX, scaleY, props.originX, props.originY);

//也可以通过设置transform来指定变换操作
  if (props.transform != null) {
    pooledTransform.transform(props.transform);
  }

  return [
    pooledTransform.xx, pooledTransform.yx,
    pooledTransform.xy, pooledTransform.yy,
    pooledTransform.x,  pooledTransform.y,
  ];
}

so 我们可以这样用

let trans=new Transform();

trans.rotate(90);

<Shape d={pathCircle} strokeWidth={20} stroke="#0FF000" strokeCap="round"
                        x={120} y={60} transform={trans}/>

位移(120,60) 旋转90度

Text组件也差不多的 这里就不多说了

Group:
可以用Group来包括多个画图组件

java层的实现

var NativeSurfaceView = createReactNativeComponentClass({
  validAttributes: SurfaceViewAttributes,
  uiViewClassName: 'ARTSurfaceView',
});

var NativeGroup = createReactNativeComponentClass({
  validAttributes: GroupAttributes,
  uiViewClassName: 'ARTGroup',
});

var NativeShape = createReactNativeComponentClass({
  validAttributes: ShapeAttributes,
  uiViewClassName: 'ARTShape',
});

var NativeText = createReactNativeComponentClass({
  validAttributes: TextAttributes,
  uiViewClassName: 'ARTText',
});

Surface Group Text Shape都对应一个ViewManager、先看看ARTSurfaceView

public class ARTSurfaceView extends TextureView 

ARTSurfaceView继承了TextureView

TextureView是个和SurfaceView差不多的东西 , 和TextView无关

TextureView的回调接口是

private SurfaceTextureListener mListener;

SurfaceTexture准备好了 改变大小都会回调接口方法

当SurfaceTexture准备好的时候我们就可以开始绘制了

public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height);

public class ARTSurfaceViewManager extends
    BaseViewManager<ARTSurfaceView, ARTSurfaceViewShadowNode> {

  @Override
  public void updateExtraData(ARTSurfaceView root, Object extraData) {
    root.setSurfaceTextureListener((ARTSurfaceViewShadowNode) extraData);
  }
}

设置的回调是ARTSurfaceViewShadowNode

看看ARTSurfaceViewShadowNode是怎么绘制的

@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
  mSurface = new Surface(surface);
  drawOutput();
}

drawOutput:

private void drawOutput() {
  if (mSurface == null || !mSurface.isValid()) {
    markChildrenUpdatesSeen(this);
    return;
  }

  try {
//获取canvas对象
    Canvas canvas = mSurface.lockCanvas(null);
    canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);

    Paint paint = new Paint();
//绘制子node
    for (int i = 0; i < getChildCount(); i++) {
      ARTVirtualNode child = (ARTVirtualNode) getChildAt(i);
      child.draw(canvas, paint, 1f);
      child.markUpdateSeen();
    }

    if (mSurface == null) {
      return;
    }

    mSurface.unlockCanvasAndPost(canvas);
  } catch (IllegalArgumentException | IllegalStateException e) {
    FLog.e(ReactConstants.TAG, e.getClass().getSimpleName() + " in Surface.unlockCanvasAndPost");
  }
}

可以看到具体的绘制操作由子node ARTVirtualNode去完成

Group Text Shape对应的viewmanager都是ARTRenderableViewManager

只是传入的classname参数不一样

public class ARTTextViewManager extends ARTRenderableViewManager {

  /* package */ ARTTextViewManager() {
    super(CLASS_TEXT);
  }
}

@Override
protected View createViewInstance(ThemedReactContext reactContext) {
  throw new IllegalStateException("ARTShape does not map into a native view");
}

在createViewInstance方法中并没有具体实现 表示ARTRenderableViewManager包含的并不是一个真正的view而是一个可绘制对象RenderableView

而这个可绘制的对象就是ReactShadowNode 返回的是ARTVirtualNode实现

@Override
public ReactShadowNode createShadowNodeInstance() {
  if (CLASS_GROUP.equals(mClassName)) {
    return new ARTGroupShadowNode();
  } else if (CLASS_SHAPE.equals(mClassName)) {
    return new ARTShapeShadowNode();
  } else if (CLASS_TEXT.equals(mClassName)) {
    return new ARTTextShadowNode();
  } else {
    throw new IllegalStateException("Unexpected type " + mClassName);
  }
}

根据classname去返回不同的ARTVirtualNode

classname有三个:

static final String CLASS_GROUP = "ARTGroup";
/* package */ static final String CLASS_SHAPE = "ARTShape";
/* package */ static final String CLASS_TEXT = "ARTText";

ARTVirtualNode中有一个draw方法来实现具体绘制

也就是说在js层的shape text group 都分别对应了java层一个ARTVirtualNode

以ARTShapeShadowNode为例:

@Override
public void draw(Canvas canvas, Paint paint, float opacity) {
  opacity *= mOpacity;
  if (opacity > MIN_OPACITY_FOR_DRAW) {
    saveAndSetupCanvas(canvas);
    if (mPath == null) {
      throw new JSApplicationIllegalArgumentException(
          "Shapes should have a valid path (d) prop");
    }
    if (setupFillPaint(paint, opacity)) {
      canvas.drawPath(mPath, paint);
    }
    if (setupStrokePaint(paint, opacity)) {
      canvas.drawPath(mPath, paint);
    }
    restoreCanvas(canvas);
  }
  markUpdateSeen();
}

主要是drawPath path就是通过<Shape/>中的d参数传入的path转换得出

@ReactProp(name = "d")
public void setShapePath(@Nullable ReadableArray shapePath) {
//把ReadableArray转成float[]
  float[] pathData = PropHelper.toFloatArray(shapePath);
  mPath = createPath(pathData);
  markUpdated();
}

shapePath在js层中就是SerializablePath中的path数组对象
onMove: function(sx, sy, x, y) {
  this.path.push(MOVE_TO, x, y);
},

path数组对象保存了要对path的操作类型 参数

java中解析SerializablePath.path中保存的操作,基本上就是读取type 接着读取后面的参数 支持的操作类型有 moveto close lineto curveto arcto

private Path createPath(float[] data) {
    Path path = new Path();
    path.moveTo(0, 0);
    int i = 0;
    while (i < data.length) {
      int type = (int) data[i++];
      switch (type) {
        case PATH_TYPE_MOVETO:
          path.moveTo(data[i++] * mScale, data[i++] * mScale);
          break;
        case PATH_TYPE_CLOSE:
          path.close();
          break;
        case PATH_TYPE_LINETO:
          path.lineTo(data[i++] * mScale, data[i++] * mScale);
          break;
        case PATH_TYPE_CURVETO:
          path.cubicTo(
              data[i++] * mScale,
              data[i++] * mScale,
              data[i++] * mScale,
              data[i++] * mScale,
              data[i++] * mScale,
              data[i++] * mScale);
          break;
        case PATH_TYPE_ARC:
        {
          float x = data[i++] * mScale;
          float y = data[i++] * mScale;
          float r = data[i++] * mScale;
          float start = (float) Math.toDegrees(data[i++]);
          float end = (float) Math.toDegrees(data[i++]);

          boolean clockwise = data[i++] == 1f;
          float sweep = end - start;
          if (Math.abs(sweep) > 360) {
            sweep = 360;
          } else {
            sweep = modulus(sweep, 360);
          }
          if (!clockwise && sweep < 360) {
            start = end;
            sweep = 360 - sweep;
          }

          RectF oval = new RectF(x - r, y - r, x + r, y + r);
          path.arcTo(oval, start, sweep);
          break;
        }
        default:
          throw new JSApplicationIllegalArgumentException(
              "Unrecognized drawing instruction " + type);
      }
    }
    return path;
  }
}

但是我们看js中提供的Path的arc方法

arc: function(x, y, rx, ry, outer, counterClockwise, rotation)

它没有直接使用java中Path. addArc的方法参数,而是改成使用终点坐标和起点坐标经过计算画圆弧的方式 这样我们如果要画扇形就比较蛋疼了~~

public void addArc(float left, float top, float right, float bottom, float startAngle,
        float sweepAngle) {

为了方便画扇形 我们可以修改js层的SerializablePath

arcTo( x,  y,  r,  start,  end,
       ccw){
    this.base.path.push(Method.ARC, x, y, r, start, end, ccw ? 0 : 1);

    return this;
}

直接往path数组对象中push参数就可以了

到这里已经完全清楚js层是如何实现画图操作的了

image.png

art包的扩展

通过上面的了解 我们可以知道art中只提供了path text的绘制,而在android中我们可以通过canvas去绘制一些图形 这样比较方便

现在我们要吧canvas的绘制方法也开放给js层使用

上面我们知道绘制操作是通过shadow node 调用子node的draw方法完成 所以要扩展绘图api 只要自定义一个ARTVirtualNode就可以了

public class CanvasViewManager extends ViewManager<View, ReactShadowNode> 

public class CanvasNode extends ARTVirtualNode 

具体实现篇幅有点长 所以就不贴在这里了,感兴趣的朋友可以直接看demo

最后用Canvas的api去绘制一个简单的进度条 意思一下~

 let circle=new Canvas();

 circle.setPaintStyle(Paint.Style.FILL);

 circle.setPaintColor("#088000");

 let angle=this.state.progress/100 * 360;

 circle.drawArc(0,0,400,400,0,angle,true);

 circle.setPaintColor("#E5E5E5");

 circle.drawCircle(200,200,100);

 circle.setPaintColor("#088000");

 circle.setPaintTextSize(49);

 let text=this.state.progress+"%";

 circle.drawText(text,0,text.length,200,200);
        

test.gif

平时比较少写文章,描述的不太清楚的,见谅,见谅~~
demo:https://github.com/shen-will/RnCanvas

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,386评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,142评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,704评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,702评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,716评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,573评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,314评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,230评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,680评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,873评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,991评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,706评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,329评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,910评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,038评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,158评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,941评论 2 355

推荐阅读更多精彩内容