1

我在 iPhone 应用程序中工作,我试图从单个图像中分割多个部分,但我无法获得确切的解决方案。我想要单个图像切片多个部分,如 3x3、4x4、5x5、6x6 等......怎么做?是否有可能做到这一点?请帮我。

提前致谢

我试过这个:

UIImage* whole = [UIImage imageNamed:@"1.png"];
    int partId = 0;
    for (int x=0; x<=300; x+=100)
    {
        for(int y=0; y<=300; y+=100)
        {

            CGImageRef cgImg = CGImageCreateWithImageInRect(whole.CGImage, CGRectMake(x, y, 100, 100));
            UIImage* part = [UIImage imageWithCGImage:cgImg];
            UIImageView* iv = [[UIImageView alloc] initWithImage:part];

            switch (partId)
            {
                case 0:
                    img.image=iv.image;
                    break;
                case 1:
                    img2.image=iv.image;
                    break;
                case 2:
                    img3.image=iv.image;
                    break;
                case 3:
                    img4.image=iv.image;
                    break;
                case 4:
                    img5.image=iv.image;
                    break;
                case 5:
                    img6.image=iv.image;
                    break;
                case 6:
                    img7.image=iv.image;
                    break;
                case 7:
                    img8.image=iv.image;
                    break;
                case 8:
                    img9.image=iv.image;
                    break;
                default:
                    break;
            }

            partId++;
            NSLog(@"part id = %d",partId);
        }
    }
4

1 回答 1

2

尝试这个:

- (NSArray*)splitImageIntoRects:(CGImageRef)anImage
{
    CGSize imageSize = CGSizeMake(CGImageGetWidth(anImage), CGImageGetHeight(anImage));

    NSMutableArray *splitLayers = [NSMutableArray array];

    kXSlices = 3;
    kYSlices = 3;        

    for(int x = 0;x < kXSlices;x++) {
        for(int y = 0;y < kYSlices;y++) {
            CGRect frame = CGRectMake((imageSize.width / kXSlices) * x,
                                 (imageSize.height / kYSlices) * y,
                                 (imageSize.width / kXSlices),
                                 (imageSize.height / kYSlices));

            CALayer *layer = [CALayer layer];
            layer.frame = frame;                                                    
            CGImageRef subimage = CGImageCreateWithImageInRect(drawnImage, frame);
            layer.contents = (id)subimage;
            CFRelease(subimage);
            [splitLayers addObject:layer];
        }
    }
    return splitLayers; 
}

注意:要获得 CGImageRef:

CGImageRef anImage = [myUIImage CGImage];

将 CGImageRef 转换为 UIImage

CALayer *layer = [splitLayers objectAtIndex:0];
CGImageRef imgRef = layer.contents;
UIImage *img = [[UIImage alloc] initWithCGImage:imgRef];
ImageView1.image = img;
于 2013-04-23T12:45:07.260 回答