绘图mask

绘图Mask
@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.
    // 设置主视图的背景色
    self.view.backgroundColor = [UIColor colorWithRed:0.2f green:0.2f blue:0.2f alpha:1.0f];
    
    // 创建一个红色背景的矩形图
    UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(100.0f, 130.0f, Width, Width)];
    aView.backgroundColor = [UIColor redColor];
    [self.view addSubview:aView];
    
    _myView = aView;
    
    UIScrollView *aScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, Width, Width)];
    aScrollView.contentSize = CGSizeMake(Width*2, Width);
    [aView addSubview:aScrollView];
    
    UIImageView *aImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, Width, Width)];
    aImageView.image = [UIImage imageNamed:@"234"];
    [aScrollView addSubview:aImageView];
    
    UIImageView *myView = [[UIImageView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, Width, Width)];
    myView.image = [UIImage imageNamed:@"456"];
    myView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:myView];

    // 将掩模视图的layer作为被裁减视图的layer的mask
    aView.layer.mask = myView.layer;

    // 注意,这里的myView不能调release方法,
    // 因为aView.layer.mask = myView.layer这句并没有将myView给retain住。
  
//    UIView *abView = [[UIView alloc] initWithFrame:CGRectMake(40.0f, 130.0f, 50.0f, 160.0f)];
//    abView.backgroundColor = [UIColor orangeColor];
//    [self.view addSubview:abView];
//    
//    UIView *abcView = [[UIView alloc] initWithFrame:CGRectMake(270.0f, 130.0f, 160.0f, 160.0f)];
//    abcView.backgroundColor = [UIColor orangeColor];
//    [self.view addSubview:abcView];

}

- (IBAction)clickMask:(id)sender
{
    static int i = 0;
    i++;
    
    UIGraphicsBeginImageContextWithOptions(_myView.bounds.size, NO, [UIScreen mainScreen].scale);
    [_myView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *iImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    NSData *imageData = UIImagePNGRepresentation(iImage);
    
    NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString*path=[paths objectAtIndex:0];
    NSLog(@"path:%@",path);
    
    [imageData writeToFile:[NSString stringWithFormat:@"%@/%d.png",path,i] atomically:YES];
    
}

234.png


456.png

猜你喜欢

转载自blog.csdn.net/lipeiran1987/article/details/52584205