ios - 截取 UIView iOS 的屏幕截图

标签 ios objective-c uiview

我想截取UIView(该 View 将包含签名)并将其保存到应用程序文件中的本地文件中,以便以后调用图像点显示在类似于 UIImageView 的内容中。下面是签名 UIView 背后的代码。

#import "NISignatureViewQuartz.h"
#import <QuartzCore/QuartzCore.h>

@implementation NISignatureViewQuartz

UIBezierPath *path;

- (void)commonInit
{
    path = [UIBezierPath bezierPath];

    // Capture touches
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    pan.maximumNumberOfTouches = pan.minimumNumberOfTouches = 1;
    [self addGestureRecognizer:pan];

    // Erase with long press
    [self addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(erase)]];

}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder]) [self commonInit];
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) [self commonInit];
    return self;
}

- (void)erase
{
    path = [UIBezierPath bezierPath];
    [self setNeedsDisplay];
}

- (void)pan:(UIPanGestureRecognizer *)pan {
    CGPoint currentPoint = [pan locationInView:self];

    if (pan.state == UIGestureRecognizerStateBegan) {
        [path moveToPoint:currentPoint];
    } else if (pan.state == UIGestureRecognizerStateChanged)
        [path addLineToPoint:currentPoint];

    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect
{
    [[UIColor blackColor] setStroke];
    [path stroke];
}

@end

我该怎么做?

最佳答案

您想将 View 的图层渲染到图形上下文中。这非常简单。在您的 NISignatureViewQuartz 类中,您可以添加此方法:

- (UIImage *)snapshot {
    UIGraphicsBeginImageContext(self.frame.size);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

关于ios - 截取 UIView iOS 的屏幕截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23785817/

相关文章:

ios - Swift 中的复杂导航堆栈

iphone - 发布到 Google+(Google 加)

iphone - iOS - 如何在 View 中绘制透明三角形

ios - 从 IOS 上的通知操作按钮打开特定应用程序?

ios - 如何设置 UIView 的来源引用?

ios - 我应该为 Pod 使用 Swift 4 迁移工具吗?

ios - 如何在Scenekit场景编辑器中设置漫反射贴图

javascript - 使用 UIWebView 时奇怪的填充/边距

ios - 自定义 UISlider 不会结束

ios - 在另一个自定义 ViewController 中更改自定义 UIView 的变量