Impossible to rende an CIImage at a position under MTKview

here is my code:


class MetalImageView : MTKView {

var image: CIImage?

var rect: CGRect?

var ciContext : CIContext?

let cs = CGColorSpaceCreateDeviceRGB()

lazy var commandQueue: MTLCommandQueue =

{

[unowned self] in

return self.device!.newCommandQueue()

}()

func clean() {

image = nil

rect = nil

}

func updateImage(image: CIImage, rect: CGRect) {

self.image = image

self.rect = rect

}

override func drawRect(rect: CGRect) {

if (image != nil) {

let commandBuffer = commandQueue.commandBuffer()

let outputTexture = currentDrawable?.texture

var drawingRect = self.rect!

drawingRect.origin.x = 200.0

drawingRect.origin.y = 200.0

ciContext?.render(image!, toMTLTexture: outputTexture!, commandBuffer: commandBuffer, bounds: drawingRect, colorSpace: cs!)

commandBuffer.presentDrawable(currentDrawable!)

commandBuffer.commit()

}

}

}


The image is always shown at the postion x = 0.


Please advice

Answered by YuAo in 138529022

How about using a transform filter (CIAffineTransform).


You can first translate your image, then create a transparent background to match the size of your view and call imageByCompositingOverImage to make the result CIImage matches the size of your MTKView.


let inputImage = ...//your image
let translatedImage = inputImage.imageByApplyingTransform(CGAffineTransformMakeTranslation(200, 200)/*your translate transform*/)

let canvas = CIImage(color: CIColor(red: 0, green: 0, blue: 0, alpha: 0)).imageByCroppingToRect(CGRectMake(0,0,/*ViewPixelWidth*/,/*ViewPixelHeight*/))
let outputImage = translatedImage.imageByCompositingOverImage(canvas)

//Render "outputImage" to your view
Accepted Answer

How about using a transform filter (CIAffineTransform).


You can first translate your image, then create a transparent background to match the size of your view and call imageByCompositingOverImage to make the result CIImage matches the size of your MTKView.


let inputImage = ...//your image
let translatedImage = inputImage.imageByApplyingTransform(CGAffineTransformMakeTranslation(200, 200)/*your translate transform*/)

let canvas = CIImage(color: CIColor(red: 0, green: 0, blue: 0, alpha: 0)).imageByCroppingToRect(CGRectMake(0,0,/*ViewPixelWidth*/,/*ViewPixelHeight*/))
let outputImage = translatedImage.imageByCompositingOverImage(canvas)

//Render "outputImage" to your view

Hi YuAo


yes, I know is this solution. But What I wonder is the performance. In my drawing application, the performance is very critical. Your solution transformes a small image to big one.


Best regards

Impossible to rende an CIImage at a position under MTKview
 
 
Q