调整裁剪图像的大小

时间:2016-09-05 17:07:47

标签: objective-c uiimageview uiimage resize crop

与此帖有类似的问题: How to remove the transparent area of an UIImageView after masking?

但是解决方案并没有帮助我,在我的情况下我将图像裁剪为多个部分,并且每个部分都有像父图像那样的边界,这就是裁剪功能:

- (UIImage*) maskImage:(CALayer *) sourceLayer toAreaInsidePath:(UIBezierPath*) maskPath;
{
    return [self compositeImage:sourceLayer onPath:maskPath usingBlendMode:kCGBlendModeSourceIn];
}

- (UIImage*) compositeImage:(CALayer *) layer onPath:(UIBezierPath*) path usingBlendMode:(CGBlendMode) blend;
{
    UIGraphicsBeginImageContext([layer frame].size);
    [layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *sourceImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIGraphicsBeginImageContext([layer frame].size);
    [path fill];
    [sourceImage drawInRect:[layer frame] blendMode:blend alpha:1.0];
    UIImage *maskedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return maskedImage;
}

以及我如何使用它:

- (PuzzlePart *)calculate:(NSDictionary *) item
{
    UIBezierPath *path = [self calculatePath:[item objectForKey:@"figure"]];
    UIImageView *iView = [[UIImageView alloc] initWithImage:image];
    //iView.contentMode = UIViewContentModeCenter;
    UIImage *imagePart = [self maskImage:iView.layer toAreaInsidePath:path];
    iView.image = imagePart;
    return [[PuzzlePart alloc] initWithParams:imagePart lhckID:lifehackID];
}

- (UIBezierPath *)calculatePath:(NSArray *) points {
    UIBezierPath *path = [UIBezierPath bezierPath];
    NSDictionary *point = [points objectAtIndex:0];
    [path moveToPoint:CGPointMake([point[@"x"] intValue], [point[@"y"] intValue])];
    for (int i = 1; i < [points count]; i++) {
        point = [points objectAtIndex:i];
        [path addLineToPoint:CGPointMake([point[@"x"] intValue], [point[@"y"] intValue])];
    }
    [path closePath];
    return path;
}

并放置它:

- (void)placeItems
{
    for (PuzzlePart *part in puzzleParts) {
        UIImage *imagePart = [part imagePart];
        CGRect newRect = [self cropRectForImage:imagePart];
        UIImage *image = [self imageWithImage:imagePart convertToSize:newRect.size];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        //imageView.contentMode = UIViewContentModeCenter;
        imageView.center = CGPointMake([self getRandomNumberBetween:0 to:self.view.frame.size.width],
                                       [self getRandomNumberBetween:0 to:self.view.frame.size.height]);
        [self.view addSubview:imageView];
        while ([self viewIntersectsWithAnotherView:self.view chosenView:imageView]) {
            viewPositionMovingStep++;
            [self placeItem:self.view:imageView];
        }
    }
    [self startCountdown];
}

[self cropRectForImage:imagePart]与我标记的帖子相同 这就是我所拥有的:

enter image description here

任何想法?谢谢!

0 个答案:

没有答案