Rendering small CIImage centered in MTKView

你。 提交于 2019-12-23 04:58:19

问题


I'm rendering a CIImage to MTKView and the image is smaller than the drawable.

let centered = image.transformed(by: CGAffineTransform(translationX: (view.drawableSize.width - image.extent.width) / 2, y: (view.drawableSize.height - image.extent.height) / 2))
context.render(centered, to: drawable.texture, commandBuffer: buffer, bounds: centered.extent, colorSpace: CGColorSpaceCreateDeviceRGB())

I'd expect the code above to render the image in the center of the view, but the image is positioned at origin instead.

Here's the repo illustrating the problem: https://github.com/truemetal/centered-render-of-ciimage-to-mtkview

Before blaming Metal or CoreImage I'd like to make sure I'm not doing something wrong.

I'd appreciate a link to the documentation that says I can't do something like that.

I can workaround this by compositing the image over another one that would be exactly the size of the drawable like so, but I'm still interested in why exactly the code above does not work.

let centered = image.transformed(by: CGAffineTransform(translationX: (view.drawableSize.width - image.extent.width) / 2, y: (view.drawableSize.height - image.extent.height) / 2))
let background = CIImage(color: .white).cropped(to: CGRect(origin: .zero, size: view.drawableSize))
let preparedImage = centered.composited(over: background)
self.context.render(preparedImage, to: drawable.texture, commandBuffer: buffer, bounds: preparedImage.extent, colorSpace: CGColorSpaceCreateDeviceRGB())

回答1:


This is most curious. If you use the "new" CIRenderDestination API instead of context.render(…) it actually works:

let destination = CIRenderDestination(width: Int(view.drawableSize.width),
                                      height: Int(view.drawableSize.height),
                                      pixelFormat: view.colorPixelFormat,
                                      commandBuffer: buffer,
                                      mtlTextureProvider: { () -> MTLTexture in
                                          return drawable.texture
                                      })
try! self.context.startTask(toRender: centered, to: destination)

I don't know why, but context.render(…) doesn't seem to respect the translation of the image or the given bounds. Maybe someone else knows more...



来源:https://stackoverflow.com/questions/54773533/rendering-small-ciimage-centered-in-mtkview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!