在UIImage上绘制另一个图像

时间:2011-07-11 21:21:42

标签: iphone objective-c uiimageview uiimage drawing

是否可以将另一个较小的图像添加到UIImage / UIImageView?如果是这样,怎么样?如果没有,那我怎么画一个小的三角形?

由于

2 个答案:

答案 0 :(得分:38)

您可以为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();

此代码(source here)将创建一个新UIImage,您可以使用它来初始化UIImageView

答案 1 :(得分:22)

你可以尝试这个,对我来说很完美,它是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;
}

或斯威夫特:

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
    }
}