IOS: How to split an UIImage into parts

泪湿孤枕 提交于 2019-12-08 02:45:40

Try This:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self getSplitImagesFromImage:[UIImage imageNamed:@"Image1.png"] withRow:4 withColumn:4];
}

-(NSMutableArray *)getSplitImagesFromImage:(UIImage *)image withRow:(NSInteger)rows withColumn:(NSInteger)columns
{
    NSMutableArray *aMutArrImages = [NSMutableArray array];
    CGSize imageSize = image.size;
    CGFloat xPos = 0.0, yPos = 0.0;
    CGFloat width = imageSize.width/rows;
    CGFloat height = imageSize.height/columns;
    for (int aIntY = 0; aIntY < columns; aIntY++)
    {
        xPos = 0.0;
        for (int aIntX = 0; aIntX < rows; aIntX++) 
        {                
            CGRect rect = CGRectMake(xPos, yPos, width, height);
            CGImageRef cImage = CGImageCreateWithImageInRect([image CGImage],  rect);

            UIImage *aImgRef = [[UIImage alloc] initWithCGImage:cImage];
            UIImageView *aImgView = [[UIImageView alloc] initWithFrame:CGRectMake(aIntX*width, aIntY*height, width, height)];
            [aImgView setImage:aImgRef];
            [aImgView.layer setBorderColor:[[UIColor blackColor] CGColor]];
            [aImgView.layer setBorderWidth:1.0];
            [self.view addSubview:aImgView];

            [aMutArrImages addObject:aImgRef];
            xPos += width;
        }
        yPos += height;
    }
    return aMutArrImages;
}

for more info see this and you can also download demo from here.

Anny

We can enhance more the Yasika Patel Answer. Below function will give you exact peice of image which fits to your view.

- (void)splitImage :(UIImage *)image withColums:(int)columns WithRows:  (int)rows ViewToIntegrate : (UIView *)view
 {
     CGSize imageSize = _imgSplit.image.size;
     CGFloat xPos = 0.0, yPos = 0.0;
     CGFloat width = imageSize.width/rows;
     CGFloat height = imageSize.height/columns;
     for (int aIntY = 0; aIntY < columns; aIntY++)
      {
        xPos = 0.0;
        for (int aIntX = 0; aIntX < rows; aIntX++)
        {
            CGRect rect = CGRectMake(xPos, yPos, width, height);
            CGImageRef cImage = CGImageCreateWithImageInRect([ image CGImage],  rect);

            UIImage *aImgRef = [[UIImage alloc] initWithCGImage:cImage];
            UIImageView *aImgView = [[UIImageView alloc] initWithFrame:CGRectMake(aIntX*(view.frame.size.width/rows), aIntY*( view.frame.size.height/columns), view.frame.size.width/rows, view.frame.size.height/columns)];

            [aImgView setImage:aImgRef];
            [aImgView.layer setBorderColor:[[UIColor blackColor] CGColor]];
            [aImgView.layer setBorderWidth:0.5];
            [view addSubview:aImgView];
            xPos += width;
        }
        yPos += height;
     }

   [self.view addSubview:view];
}

This will give you the image in 9parts . here you just need to pass the row and colums.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!