PDFBackgroundDrawImageView.m 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. //
  2. // CPDFDrawImageView.m
  3. // PDFViewer
  4. //
  5. // Created by kdanmobile_2 on 2023/1/3.
  6. //
  7. #import "PDFBackgroundDrawImageView.h"
  8. @implementation PDFBackgroundDrawImageView
  9. - (instancetype)initWithFrame:(CGRect)frame {
  10. self = [super initWithFrame:frame];
  11. if (self) {
  12. self.backgroundColor = [UIColor clearColor];
  13. }
  14. return self;
  15. }
  16. - (void)drawRect:(CGRect)rect {
  17. CGContextRef context = UIGraphicsGetCurrentContext();
  18. [self showDraw:context];
  19. }
  20. - (void)showDraw:(CGContextRef)context {
  21. UIImage *newImage = [self imageToTransparent:_image];
  22. [newImage drawInRect:self.bounds blendMode:kCGBlendModeNormal alpha:1.0f];
  23. }
  24. - (UIImage*) imageToTransparent:(UIImage*) image {
  25. const int imageWidth = image.size.width;
  26. const int imageHeight = image.size.height;
  27. size_t bytesPerRow = imageWidth * 4;
  28. uint32_t *rgbImageBuf = (uint32_t *)malloc(bytesPerRow * imageHeight);
  29. CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  30. CGContextRef context = CGBitmapContextCreate(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpace
  31. , kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
  32. CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image.CGImage);
  33. int pixelNum = imageWidth * imageHeight;
  34. uint32_t* pCurPtr = rgbImageBuf;
  35. for (int i = 0; i < pixelNum; i++, pCurPtr++)
  36. {
  37. if ((*pCurPtr & 0x65815A00) == 0x65815a00)
  38. {
  39. uint8_t* ptr = (uint8_t*)pCurPtr;
  40. ptr[0] = 0;
  41. }
  42. }
  43. CGDataProviderRef dataProvider =CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, ProviderReleaseData);
  44. CGImageRef imageRef = CGImageCreate(imageWidth, imageHeight,8, 32, bytesPerRow, colorSpace,
  45. kCGImageAlphaLast |kCGBitmapByteOrder32Little, dataProvider,
  46. NULL, true,kCGRenderingIntentDefault);
  47. CGDataProviderRelease(dataProvider);
  48. UIImage* resultUIImage = [UIImage imageWithCGImage:imageRef];
  49. CGImageRelease(imageRef);
  50. CGContextRelease(context);
  51. CGColorSpaceRelease(colorSpace);
  52. return resultUIImage;
  53. }
  54. void ProviderReleaseData(void *info, const void *data, size_t size) {
  55. free((void *) data);
  56. }
  57. @end