【问题标题】:CGBitmapContextCreate with undo not working well撤消的CGBitmapContextCreate效果不佳
【发布时间】:2019-09-22 17:57:46
【问题描述】:

我在撤销功能上苦苦挣扎了几天,我真的不知道如何解决这个问题。

我正在使用自定义 UIimageView 的 UIViewController 上制作绘图功能。

问题是当我触发撤消功能时,之前的绘图运行良好,但是当我再次尝试绘图时,删除的绘图再次出现在当前绘图中。

这是我的代码。 如果您看到任何问题,请告诉我!这将非常有帮助。 谢谢!

- (IBAction)Pan:(UIPanGestrueRecognizer *)pan {
    CGContextRef ctxt = [self drawingContext];

    CGContextBeginPath(ctxt);
    CGContextMoveToPoint(ctxt, previous.x, previous.y);
    CGContextAddLineToPoint(ctxt, current.x, current.y);
    CGContextStrokePath(ctxt);

    CGImageRef img = CGBitmapContextCreateImage(ctxt);
    self.costomImageView.image = [UIImage imageWithCGImage:img];
    CGImageRelease(img);
    previous = current;
    ...
}

- (CGContextRef)drawingContext {
    if(!context) { // context is an instance variable of type CGContextRef
        CGImageRef image = self.customImageView.image.CGImage;
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        if(!colorSpace) return nil;
        context = CGBitmapContextCreate(NULL,
                                        CGImageGetWidth(image), CGImageGetHeight(image),
                                        8, CGImageGetWidth(image) * 4,
                                        colorSpace, kCGImageAlphaPremultipliedLast
                                        );
        CGColorSpaceRelease(colorSpace);
        if(!context) return nil;
        CGContextConcatCTM(context, CGAffineTransformMake(1,0,0,-1,0,self.customeImageView.image.size.height));

        CGContextSaveGState(context);
        CGContextTranslateCTM(context, 0.0, self.customImageView.image.size.height);
        CGContextScaleCTM(context, 1.0, -1.0);
        CGContextDrawImage(context, (CGRect){CGPointZero,self.customImageView.image.size}, image);
        CGContextRestoreGState(context);

        CGContextSetLineCap(context, kCGLineCapRound);
        CGContextSetLineWidth(context, 4.f);
        CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    }
    return context;
}

【问题讨论】:

    标签: ios objective-c image core-graphics


    【解决方案1】:

    我不确定UndoManager 是否支持您尝试做的事情

    我个人会做这样的事情:

    1. 创建一个NSMutableArray 以包含您的所有绘图笔触。包含两个 Point 实例的结构应该可以完成此任务。如果你想花哨,你可以添加一个UIColor 实例来设置颜色和其他样式信息的更多变量。

    2. 当您的平移手势开始时,记录它的开始点。当它结束时,记录该点,创建一个结构实例并将其添加到数组中。

    3. 有一个渲染过程来清除图形上下文,遍历数组并绘制到屏幕上。

    对于撤消功能,您需要做的就是从数组中删除最后一个条目并重新渲染。

    【讨论】:

      猜你喜欢
      • 2013-09-06
      • 1970-01-01
      • 2019-06-10
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      • 1970-01-01
      • 2017-09-26
      • 2011-05-09
      相关资源
      最近更新 更多