Question

Trying to superimpose a smaller image which may be scaled or rotated onto a lager image:

+ (UIImage*)addToImage:(UIImage *)baseImage newImage:(UIImage*)newImage atPoint:(CGPoint)point transform:(CGAffineTransform)transform {

    UIGraphicsBeginImageContext(baseImage.size);
    [baseImage drawInRect:CGRectMake(0, 0, baseImage.size.width, baseImage.size.height)];

    [newImage drawAtPoint:point];
    //How would I apply the transform?

    UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

return result;
}

How would I apply the CGAffineTransform to newImage in this context?

Était-ce utile?

La solution

You can use the CoreImage framework, this allows transformations on CIImage instances. For example:

CGAffineTransform transform = ...;
CIImage* coreImage = newImage.CIImage;

if (!coreImage) {
    coreImage = [CIImage imageWithCGImage:newImage.CGImage];
}

coreImage = [coreImage imageByApplyingTransform:transform];
newImage = [UIImage imageWithCIImage:coreImage];

You'll need to ensure that after calling .CIImage, that is isn't nil. This will occur if the UIImage was initialised with a CGImage. If this is the case, then you'll need to allocate a CIImage yourself with the appropriate initialiser.

Autres conseils

Something like this should do it:

+ (UIImage*) addToImage:(UIImage *)baseImage newImage:(UIImage*)newImage atPoint:(CGPoint)point transform:(CGAffineTransform)transform {

    UIGraphicsBeginImageContext(baseImage.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    [baseImage drawInRect:CGRectMake(0, 0, baseImage.size.width, baseImage.size.height)];

//    [newImage drawAtPoint:point];  draw without applying the transformation

    CGRect originalRect = CGRectMake(point.x,
                                     point.y,
                                     newImage.size.width,
                                     newImage.size.height);


    CGContextConcatCTM(context, transform);
    CGContextDrawImage(context, originalRect, newImage.CGImage);

    UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return result;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top