将一个UIView的绘制内容复制到另一个UIView上

4
我想使用UITextView让用户输入文本,然后触发将内容复制到石英位图上下文中。 有人知道我如何执行此复制操作吗? 我应该覆盖drawRect方法并调用[super drawRect],然后获取结果上下文并将其复制吗? 如果是这样,是否有任何参考示例代码可从一个上下文复制到另一个上下文?
更新:从下面答案的链接中阅读后,我尝试组合以下代码以将UIView内容复制到位图上下文中,但仍有问题。 我得到我的内容在X轴上镜像(即倒置)。 我尝试使用CGContextScaleCTM(),但似乎没有效果。
我已验证前四行创建的UIImage确实创建了一个不奇怪旋转/翻转的UIImage,因此我在后续调用中做错了一些事情。
    // copy contents to bitmap context
    UIGraphicsBeginImageContext(mTextView.bounds.size);
    [mTextView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();    

    [self setNeedsDisplay];

    // render the created image to the bitmap context
    CGImageRef cgImage = [image CGImage];

    CGContextScaleCTM(mContext, 1.0, -1.0); // doesn't seem to change result

    CGContextDrawImage(mContext, CGRectMake(
        mTextView.frame.origin.x,
        mTextView.frame.origin.y,
        [image size].width, [image size].height), cgImage); 

有什么建议吗?
2个回答

1

这是我用来获取UIView UIImage的代码:

@implementation UIView (Sreenshot)

    - (UIImage *)screenshot{
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale);

        /* iOS 7 */
        BOOL visible = !self.hidden && self.superview;
        CGFloat alpha = self.alpha;
        BOOL animating = self.layer.animationKeys != nil;
        BOOL success = YES;
        if ([self respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]){
            //only works when visible
            if (!animating && alpha == 1 && visible) {
                success = [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:NO];
            }else{
                self.alpha = 1;
                success = [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
                self.alpha = alpha;
            }
        }
        if(!success){ /* iOS 6 */
            self.alpha = 1;
            [self.layer renderInContext:UIGraphicsGetCurrentContext()];
            self.alpha = alpha;
        }

        UIImage* img = UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();

        return img;
    }

@end

0

您可以在 iOS 7 及更高版本中使用:

- (UIView *)snapshotViewAfterScreenUpdates:(BOOL)afterUpdates 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接