在UIImage上绘制另一个图像

Ale*_*ede 23 iphone drawing objective-c uiimageview uiimage

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

谢谢

ser*_*gio 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();
Run Code Online (Sandbox Code Playgroud)

此代码(此处代码)将创建一个UIImage可用于初始化a 的新代码UIImageView.


iiF*_*man 24

你可以尝试这个,对我来说很完美,它是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;
}
Run Code Online (Sandbox Code Playgroud)

或斯威夫特:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这很好,谢谢。我建议您使用“ UIGraphicsBeginImageContextWithOptions(size,false,0)”。这将为您提供具有适合屏幕分辨率的图像。(默认设置只会生成x1图像,几乎可以肯定是模糊的。) (4认同)