2014년 5월 17일 토요일

grid crop with uiimage

이미지를 grid 형태로 잘라서 view에 add하는 예제.


- (void)viewDidLoad
{
    [super viewDidLoad];
    UIImage *scaledImage = [self scaleWithImage:[UIImage imageNamed:@"37.jpg"] scaledToSize:self.view.frame.size];
    self.originalImageView = [[UIImageView alloc] initWithImage:scaledImage];
    [self prepareSlices:10 :10];
}

-(void)prepareSlices:(uint)row :(uint)col
{
    float flagX = _originalImageView.image.size.width / _originalImageView.frame.size.width;
    float flagY = _originalImageView.image.size.height / _originalImageView.frame.size.height;
    
    float _width    = _originalImageView.frame.size.width / col;
    float _height   = _originalImageView.frame.size.height / row;
    
    float _posX = 0.0;
    float _posY = 0.0;
    
    for (int i = 1; i <= row * col; i++) {
        
        UIImageView *croppedImageVeiw = [[UIImageView alloc] initWithFrame:CGRectMake(_posX, _posY, _width, _height)];
        UIImage *img = [self getCropImage:CGRectMake(_posX * flagX,_posY * flagY, _width * flagX, _height * flagY)];
        croppedImageVeiw.image = img;
        
        croppedImageVeiw.layer.borderColor = [[UIColor whiteColor] CGColor];
        croppedImageVeiw.layer.borderWidth = 1.0f;
        
        [self.view addSubview:croppedImageVeiw];
        
        _posX += _width;
        
        if (i % col == 0) {
            _posX = 0;
            _posY += _height;
        }
    }
}

-(UIImage*)getCropImage:(CGRect)cropRect
{
    CGImageRef image = CGImageCreateWithImageInRect([_originalImageView.image CGImage],cropRect);
    UIImage *cropedImage = [UIImage imageWithCGImage:image];
    CGImageRelease(image);
    return cropedImage;

}

- (UIImage *)scaleWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    //UIGraphicsBeginImageContext(newSize);
    // In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
    // Pass 1.0 to force exact pixel size.
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 1.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}


댓글 없음:

댓글 쓰기