Can I edit the pixels of the UIImage's property CGImage

前端 未结 7 1462
野趣味
野趣味 2020-11-28 05:04

UIImage has a read-only property CGImage. I have to read its pixels to a memory block and edit them and then make a new UIImage to replace the old one. I want to know if th

7条回答
  •  无人及你
    2020-11-28 05:12

    I used the following code to add 2 thin red lines at right and left of an image

    -(UIImage*)ModifyImage:(UIImage*) img
    {
        UIGraphicsBeginImageContext(img.size);
    
        [img drawInRect:CGRectMake(0,0,img.size.width,img.size.height) blendMode:kCGBlendModeSourceOut alpha:1.0f];
    
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        int w =img.size.width;
        int cw,ch;
    
        cw = img.size.width / 35;
        ch = img.size.height / 35;
    
        unsigned char* data = CGBitmapContextGetData (ctx);
    
        for(int y = 0 ; y < img.size.height ; y++)
        {
            for(int x = 0 ; x < img.size.width ; x++)
            {
                //int offset = 4*((w * y) + x);
    
                int offset = (CGBitmapContextGetBytesPerRow(ctx)*y) + (4 * x);
    
                int blue    =  data[offset];
                int green   = data[offset+1];
                int red     = data[offset+2];
                //int alpha   = data[offset+3];
    
                if(x <= (cw * 2) || x >= (cw * 35))
                {
                    data[offset]    = 0;
                    data[offset+1]  = 0;
                    data[offset+2]  = 255;
                    data[offset+3]  = 255;
                }
            }
        }
    
        UIImage *rtimg = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return rtimg;
    }
    

提交回复
热议问题