我有一张这样的图片...
我需要实现的是更改这个图像下半部分的颜色,就像这个图像一样...
我尝试过使用CAGradientLayer、Masking等方法,但没有成功得到结果。
任何帮助都将不胜感激。谢谢。
更新1:
在使用以下代码后,我得到了这个结果。还有一件事要补充,那就是在使用前调整了图像大小。 更新2:
任何帮助都将不胜感激。谢谢。
更新1:
在使用以下代码后,我得到了这个结果。还有一件事要补充,那就是在使用前调整了图像大小。 更新2:
这让我面临一些挑战,但是我来试着翻译一下:
返回底部涂有某种颜色的图像的方法
- (UIImage *)image:(UIImage *)image withBottomHalfOverlayColor:(UIColor *)color
{
CGRect rect = CGRectMake(0.f, 0.f, image.size.width, image.size.height);
if (UIGraphicsBeginImageContextWithOptions) {
CGFloat imageScale = 1.f;
if ([self respondsToSelector:@selector(scale)])
imageScale = image.scale;
UIGraphicsBeginImageContextWithOptions(image.size, NO, imageScale);
}
else {
UIGraphicsBeginImageContext(image.size);
}
[image drawInRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetBlendMode(context, kCGBlendModeSourceIn);
CGContextSetFillColorWithColor(context, color.CGColor);
CGRect rectToFill = CGRectMake(0.f, image.size.height*0.5f, image.size.width, image.size.height*0.5f);
CGContextFillRect(context, rectToFill);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
使用示例:
UIImage *image = [UIImage imageNamed:@"q.png"];
image = [self image:image withBottomHalfOverlayColor:[UIColor cyanColor]];
self.imageView.image = image;
我的结果:
UIImage *bgImage = [[UIImage imageNamed:@"TM-Bubbles-Blue"] resizableImageWithCapInsets: UIEdgeInsetsMake(30, 32, 30, 23) resizingMode: UIImageResizingModeStretch];
- Ahmed Z.在 Swift 4 中,有一些变化:
func withBottomHalfOverlayColor(myImage: UIImage, color: UIColor) -> UIImage
{
let rect = CGRect(x: 0, y: 0, width: myImage.size.width, height: myImage.size.height)
UIGraphicsBeginImageContextWithOptions(myImage.size, false, myImage.scale)
myImage.draw(in: rect)
let context = UIGraphicsGetCurrentContext()!
context.setBlendMode(CGBlendMode.sourceIn)
context.setFillColor(color.cgColor)
let rectToFill = CGRect(x: 0, y: myImage.size.height*0.5, width: myImage.size.width, height: myImage.size.height*0.5)
context.fill(rectToFill)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
Swift 5 扩展
extension UIImage {
func withBottomHalfOverlayColor(color: UIColor) -> UIImage
{
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, scale)
draw(in: rect)
let context = UIGraphicsGetCurrentContext()!
context.setBlendMode(CGBlendMode.sourceIn)
context.setFillColor(color.cgColor)
let rectToFill = CGRect(x: 0, y: size.height*0.5, width: size.width, height: size.height*0.5)
context.fill(rectToFill)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
你可以使用一些技巧: