pgraphics2d应该实现cloneable,但是抛出异常

yshpjwxd  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(332)

使用java处理,我试图制作pgraphics2d对象的深度副本

PGraphics2D pg_render;
pg_render = (PGraphics2D) createGraphics(width, height, P2D);
PGraphics2D pg_postprocd = (PGraphics2D)pg_render.clone();

引发clonenotsupportedexception:
未处理的异常类型clonenotsupportedexception
然而,读了这份文件,克隆似乎已经实现了。
我需要有两个pgraphics2d对象的示例,这样我就可以对其中一个应用后处理效果,并保持另一个干净,以便分析运动矢量等。

vxqlmq5t

vxqlmq5t1#

例外情况

这个 PGraphics 类本身不实现 Clonable . 相反,它延伸了 PImage 这个类实际上实现了 Cloneable 接口。
这就是为什么你打电话给 pg_render.clone() 投掷 CloneNotSupportedException ,因为pgraphics实际上不支持克隆(但碰巧扩展了一个支持克隆的类)。

解决方案

下面的静态方法返回输入pgraphics对象的克隆。它创造了一个新的世界 PGraphics 对象 createGraphics() ,克隆样式(样式包括诸如当前填充颜色之类的内容),最后克隆像素缓冲区。

代码

static PGraphics clonePGraphics(PGraphics source) {

  final String renderer;
  switch (source.parent.sketchRenderer()) {
    case "processing.opengl.PGraphics2D" :
      renderer = PConstants.P2D;
      break;
    case "processing.opengl.PGraphics3D" :
      renderer = PConstants.P3D;
      break;
    default : // secondary sketches cannot use FX2D
      renderer = PConstants.JAVA2D;
  }

  PGraphics clone = source.parent.createGraphics(source.width, source.height, renderer);

  clone.beginDraw();
  clone.style(source.getStyle()); // copy style (fillColor, etc.)
  source.loadPixels(); // graphics buffer -> int[] buffer
  clone.pixels = source.pixels.clone(); // in's int[] buffer -> clone's int[] buffer
  clone.updatePixels(); // int[] buffer -> graphics buffer
  clone.endDraw();

  return clone;
}

相关问题