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); 

有什么建议么?

4

2 回答 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
于 2015-04-09T06:23:05.103 回答
0

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

- (UIView *)snapshotViewAfterScreenUpdates:(BOOL)afterUpdates 
于 2016-04-15T06:50:43.840 回答