Implementation of mac osx mosaic

Realization principle

Reference resources The implementation of mosaic with variable position of iOS finger Implement mac osx version

Image mosaic implementation

With the help of CIFilter filter in CoreImage library, we can easily implement mosaic code of pictures as follows

NSImage * img1 = [NSImage imageNamed:@"1.png"];
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge  CFDataRef)img1.TIFFRepresentation, nil);
CGImageRef inImage = CGImageSourceCreateImageAtIndex(source, 0, nil);
CIImage *ciImage  = [[CIImage alloc] initWithCGImage:inImage];
CIFilter *filter  = [CIFilter filterWithName:@"CIPixellate"];
[filter setDefaults];
[filter setValue:ciImage forKey:kCIInputImageKey];
[filter setValue:@(10.f) forKey:kCIInputScaleKey];
CIImage * outPutImg = [filter outputImage];
NSCIImageRep * rep = [NSCIImageRep imageRepWithCIImage:outPutImg];
NSImage *img2 = [[NSImage alloc] initWithSize:[outPutImg extent].size];
[img2 addRepresentation:rep];

CAShapeLayer

Display mosaic according to Path through layer mask

    //mac must set wantsLayer = YES to use the layer, and the default is NO
    self.view.wantsLayer = YES;
    //Add layer (imageLayer) to self
    self.imageLabyer = [CALayer layer];
    self.imageLabyer.frame = self.view.bounds;
    [self.view.layer addSublayer:self.imageLabyer];
    
    self.shapeLayer = [CAShapeLayer layer];
    self.shapeLayer.frame = self.view.bounds;
    self.shapeLayer.lineCap = kCALineCapRound;
    self.shapeLayer.lineJoin = kCALineJoinRound;
    self.shapeLayer.lineWidth = 40.0f;
    self.shapeLayer.strokeColor = [[NSColor blueColor] CGColor];
    self.shapeLayer.fillColor = nil;
    [self.view.layer addSublayer:self.shapeLayer];
    
    //Set mask
    self.imageLabyer.mask = self.shapeLayer;
    self.path = CGPathCreateMutable();
    //Set mosaic picture
    self.imageLabyer.contents = img2;
    //Set base map
    self.view.layer.contents = img1;

Mouse response processing

Set View to listen to mouse movement messages
[self.view addTrackingRect:self.view.bounds owner:self userData:nil assumeInside:YES];

Handle mouse movement messages

- (void)mouseDown:(NSEvent *)event
{
   CGPoint pt = event.locationInWindow;
   CGPathMoveToPoint(self.path, NULL, pt.x, pt.y);
   CGMutablePathRef path = CGPathCreateMutableCopy(self.path);
   self.shapeLayer.path = path;
   CGPathRelease(path);
   NSLog(@"mouseDown");
}

-(void)mouseUp:(NSEvent *)event
{
    NSLog(@"mouseUp");
}
-(void)mouseDragged:(NSEvent *)event
{
   CGPoint pt = event.locationInWindow;
   CGPathAddLineToPoint(self.path, NULL,pt.x, pt.y);
   CGMutablePathRef path = CGPathCreateMutableCopy(self.path);
   self.shapeLayer.path = path;
   CGPathRelease(path);
   NSLog(@"mouseDragged");
}

Design sketch

Design sketch

Source code

Shenzhen Licheng Electronic Co., Ltd

Tags: Mac iOS

Posted on Mon, 02 Dec 2019 01:22:11 -0500 by fishown