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

2024-03-11

我想采用 UITextView 并允许用户在其中输入文本,然后触发将内容复制到石英位图上下文上。有谁知道我如何执行此复制操作?我应该重写drawRect方法并调用[super drawRect]并且then获取生成的上下文并复制它?如果是这样,是否有人可以参考示例代码从一个上下文复制到另一个上下文?

更新:通过阅读下面答案中的链接,我将这么多内容放在一起尝试将我的 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); 

有什么建议么?


这是我用来获取 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将一个 UIView 的绘制内容复制到另一个 UIView 的相关文章

随机推荐