我首先将图像转换为原始像素,然后再次将像素转换回 UIImage,在转换图像后它会改变颜色并变得透明,我尝试了很多但无法解决问题。这是我的代码:
-(UIImage*)markPixels:(NSMutableArray*)pixels OnImage:(UIImage*)image{ CGImageRef inImage = image.CGImage; // Create off screen bitmap context to draw the image into. Format ARGB is 4 bytes for each pixel: Alpa, Red, Green, Blue CGContextRef cgctx = [self createARGBBitmapContextFromImage:inImage]; if (cgctx == NULL) { return nil; /* error */ } size_t w = CGImageGetWidth(inImage); size_t h = CGImageGetHeight(inImage); CGRect rect = {{0,0},{w,h}}; // Draw the image to the bitmap context. Once we draw, the memory // allocated for the context for rendering will then contain the // raw image data in the specified color space. CGContextDrawImage(cgctx, rect, inImage); // Now we can get a pointer to the image data associated with the bitmap // context. int r = 3; int p = 2*r+1; unsigned char* data = CGBitmapContextGetData (cgctx); int i = 0; while (data[i]&&data[i+1]) { // NSLog(@"%d",pixels[i]); i++; } NSLog(@"%d %zd %zd",i,w,h); NSLog(@"%ld",sizeof(CGBitmapContextGetData (cgctx))); for(int i = 0; i< pixels.count-1 ; i++){ NSValue*touch1 = [pixels objectAtIndex:i]; NSValue*touch2 = [pixels objectAtIndex:i+1]; NSArray *linePoints = [self returnLinePointsBetweenPointA:[touch1 CGPointValue] pointB:[touch2 CGPointValue]]; for(NSValue *touch in linePoints){ NSLog(@"point = %@",NSStringFromCGPoint([touch CGPointValue])); CGPoint location = [touch CGPointValue]; for(int i = -r ; i<p ;i++) for(int j= -r; j<p;j++) { if(i<=0 && j<=0 && i>image.size.height && j>image.size.width) continue; NSInteger index = (location.y+i) * w*4 + (location.x+j)* 4; index = 0; data[index +3] = 125; } } } // When finished, release the context CGContextRelease(cgctx); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGDataProviderRef dp = CGDataProviderCreateWithData(NULL, data, w*h*4, NULL); CGImageRef img = CGImageCreate(w, h, 8, 32, 4*w, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big, dp, NULL, NO, kCGRenderingIntentDefault); UIImage* ret_image = [UIImage imageWithCGImage:img]; CGImageRelease(img); CGColorSpaceRelease(colorSpace); // Free image data memory for the context if (data) { free(data); } return ret_image; }
第一个是原始图像,第二个图像是应用此代码后的图像。