我不确定如何命名,抱歉标题。
我想要根据变量或多或少地填充图像。为此,我创建了一个由黑色和白色组成的图像(下图)。目标是将其用作蒙版并根据此documentation以我想要的方式填充。
问题:图像绘制正确但尺寸太高。我使用@ 3x图像在iPhone 6+上测试它,图像资源大小是正确的但是我的功能返回的图像太大了。当我在UIImageView *上设置约束时,我只查看返回的填充图像的一部分;当我不在时,图像太大了。请参阅下面的截图(iPhone 6 +)
我使用以下代码将UIView子类化:
- (void)drawRect:(CGRect)rect
{
CGFloat width = self.frame.size.width;
NSLog(@"%0.f", width);
CGFloat height = self.frame.size.height;
NSLog(@"%0.f", height);
CGFloat fillHeight = 0.9 * height;
NSLog(@"%0.f", fillHeight);
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect fillRect = CGRectMake(0, height - fillHeight, width, fillHeight);
CGContextAddRect(context, fillRect);
CGContextSetFillColorWithColor(context, [UIColor yellowColor].CGColor);
CGContextFillRect(context, fillRect);
CGRect emptyRect = CGRectMake(0, 0, width, height - fillHeight);
CGContextAddRect(context, emptyRect);
CGContextSetFillColorWithColor(context, [UIColor blueColor].CGColor);
CGContextFillRect(context, emptyRect);
}
- (UIImage *)renderAsImage
{
// setup context
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0); // use same scale factor as device
CGContextRef c = UIGraphicsGetCurrentContext();
// render view
[self.layer renderInContext:c];
// get reslting image
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
NSLog(@"result size = %d width, %d height", result.size.width, result.size.height);
UIGraphicsEndImageContext();
return result;
}
在我的ViewController中:
- (void) setUpMaskedImage
{
// Image View set in Storyboard that will contain the final image. Bounds are set in Storyboard (constraints)
UIImageView* imageView = self.containingImageView;
// Custom View (see methods above) that will draw a rectangle filled with color
UIView* view = [[CustomView alloc] initWithFrame: imageView.frame];
// Mask Image used along with the custom view to create final view (see image above)
UIImage* maskImage = [UIImage imageNamed: @"maskImage"];
[view setNeedsDisplay];
UIImage* fillImage = [view renderAsImage];
CGImageRef maskRef = maskImage.CGImage;
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef), NULL, false);
CGImageRef masked = CGImageCreateWithMask([image CGImage], mask);
UIImage* imageToDisplay = [UIImage imageWithCGImage:masked];
[imageView setImage:imageToDisplay];
}
我只是不明白。我在我的应用程序的其他地方使用了类似的代码,它工作正常。如有必要,我会尽快做一个示例项目。
谢谢!