【问题标题】:Copying the drawn contents of one UIView to another将一个 UIView 的绘制内容复制到另一个
【发布时间】:2010-10-27 15:22:06
【问题描述】:

我想要一个 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); 

有什么建议吗?

【问题讨论】:

    标签: cocoa uiview copy cgcontext quartz-2d


    【解决方案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
    

    【讨论】:

      【解决方案2】:

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

      - (UIView *)snapshotViewAfterScreenUpdates:(BOOL)afterUpdates 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-25
        • 1970-01-01
        • 2012-01-16
        • 1970-01-01
        相关资源
        最近更新 更多