在UIImage上绘制另一张图片

26

能否向UIImage / UIImageView添加另一个较小的图像?如果可以,怎么做?如果不行,那么如何绘制一个小的填充三角形?

谢谢。

2个回答

44

您可以将一个包含小实心三角形的图像添加为您的 UIImageView 的子视图。或者您可以在第一幅图像内绘制:

CGFloat width, height;
UIImage *inputImage;    // input image to be composited over new image as example

// create a new bitmap image context at the device resolution (retina/non-retina)
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), YES, 0.0);        

// get context
CGContextRef context = UIGraphicsGetCurrentContext();       

// push context to make it current 
// (need to do this manually because we are not drawing in a UIView)
UIGraphicsPushContext(context);                             

// drawing code comes here- look at CGContext reference
// for available operations
// this example draws the inputImage into the context
[inputImage drawInRect:CGRectMake(0, 0, width, height)];

// pop context 
UIGraphicsPopContext();                             

// get a UIImage from the image context- enjoy!!!
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();

// clean up drawing environment
UIGraphicsEndImageContext();

这段代码(源代码在此)可以创建一个新的UIImage,你可以用它来初始化一个UIImageView


31

你可以尝试这个,对我来说效果非常完美,它是UIImage类别:

- (UIImage *)drawImage:(UIImage *)inputImage inRect:(CGRect)frame {
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
    [self drawInRect:CGRectMake(0.0, 0.0, self.size.width, self.size.height)];
    [inputImage drawInRect:frame];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

或者Swift:

extension UIImage {
    func image(byDrawingImage image: UIImage, inRect rect: CGRect) -> UIImage! {
        UIGraphicsBeginImageContext(size)
        draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        image.draw(in: rect)
        let result = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return result
    }
}

谢谢,伙计。这是一个非常有用的代码片段。 - Rostyslav Druzhchenko
5
谢谢,这个方法很有效。我建议您使用'UIGraphicsBeginImageContextWithOptions(size, false, 0)',这将为您提供屏幕分辨率正确的图像。(默认设置只会生成x1图像,几乎肯定会模糊)。 - Womble
我想将结果图像转换为cvBufferPixel,但它不包含CIImage,你能帮忙吗? - famfamfam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接