문제

나는 현재 Uiimage (흰색)에 검은 색 오버레이를 추가하려고합니다. 다음 코드를 사용하려고 노력했습니다.

[[UIColor blackColor] set];
[image drawAtPoint:CGPointMake(0, 0) blendMode:kCGBlendModeOverlay alpha:1.0];

그러나 그것은 작동하지 않으며, 나는 세트가 거기에 없어야한다고 확신합니다.

도움이 되었습니까?

해결책

컨텍스트를 이미지 마스크에 클립 한 다음 단색으로 채우고 싶을 것입니다.

- (void)drawRect:(CGRect)rect
{
    CGRect bounds = [self bounds];
    [[UIColor blackColor] set];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClipToMask(context, bounds, [myImage CGImage]);
    CGContextFillRect(context, bounds);
}

메모: myImage an을 포함하는 인스턴스 변수 여야합니다 UIImage. 알파 채널에서 마스크를 가져 가는지 또는 강도를 가져 오는지 확실하지 않으므로 둘 다 시도하십시오.

다른 팁

따라서 모든 답변을 하나로 요약하려면 여기에 완벽하게 작동하는 드롭 인 방법이 있습니다. iOS 6 끝까지 iOS 11 모든 종류의 이미지와 아이콘으로 :

+ (UIImage *)filledImageFrom:(UIImage *)source withColor:(UIColor *)color{

    // begin a new image context, to draw our colored image onto with the right scale
    UIGraphicsBeginImageContextWithOptions(source.size, NO, [UIScreen mainScreen].scale);

    // get a reference to that context we created
    CGContextRef context = UIGraphicsGetCurrentContext();

    // set the fill color
    [color setFill];

    // translate/flip the graphics context (for transforming from CG* coords to UI* coords
    CGContextTranslateCTM(context, 0, source.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextSetBlendMode(context, kCGBlendModeColorBurn);
    CGRect rect = CGRectMake(0, 0, source.size.width, source.size.height);
    CGContextDrawImage(context, rect, source.CGImage);

    CGContextSetBlendMode(context, kCGBlendModeSourceIn);
    CGContextAddRect(context, rect);
    CGContextDrawPath(context,kCGPathFill);

    // generate a new UIImage from the graphics context we drew onto
    UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    //return the color-burned image
    return coloredImg;
}

업데이트: 스위프트 3 버전

func filledImage(source: UIImage, fillColor: UIColor) -> UIImage {

    UIGraphicsBeginImageContextWithOptions(source.size, false, UIScreen.main.scale)

    let context = UIGraphicsGetCurrentContext()
    fillColor.setFill()

    context!.translateBy(x: 0, y: source.size.height)
    context!.scaleBy(x: 1.0, y: -1.0)

    context!.setBlendMode(CGBlendMode.colorBurn)
    let rect = CGRect(x: 0, y: 0, width: source.size.width, height: source.size.height)
    context!.draw(source.cgImage!, in: rect)

    context!.setBlendMode(CGBlendMode.sourceIn)
    context!.addRect(rect)
    context!.drawPath(using: CGPathDrawingMode.fill)

    let coloredImg : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

    return coloredImg
}

방금 도움이 될 튜토리얼을 썼습니다. 내 접근 방식은 당신이 원하는 색상 변경과 함께 uiimage 사본을 제공합니다. Rpetrich의 접근 방식은 훌륭하지만 서브 클래스를 만들어야합니다. 내 접근 방식은 필요한 곳에서 삭제할 수있는 몇 줄의 코드입니다. http://coffeeshopped.com/2010/09/iphone-how-to-dynamically-color-a-uiimage

NSString *name = @"badge.png";
UIImage *img = [UIImage imageNamed:name];

// begin a new image context, to draw our colored image onto
UIGraphicsBeginImageContext(img.size);

// get a reference to that context we created
CGContextRef context = UIGraphicsGetCurrentContext();

// set the fill color
[color setFill];

// translate/flip the graphics context (for transforming from CG* coords to UI* coords
CGContextTranslateCTM(context, 0, img.size.height);
CGContextScaleCTM(context, 1.0, -1.0);

// set the blend mode to color burn, and the original image
CGContextSetBlendMode(context, kCGBlendModeColorBurn);
CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height);
CGContextDrawImage(context, rect, img.CGImage);

// set a mask that matches the shape of the image, then draw (color burn) a colored rectangle
CGContextClipToMask(context, rect, img.CGImage);
CGContextAddRect(context, rect);
CGContextDrawPath(context,kCGPathFill);

// generate a new UIImage from the graphics context we drew onto
UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

//return the color-burned image
return coloredImg;

iOS 7이므로 훨씬 간단한 솔루션이 있습니다.

UIImage* im = [UIImage imageNamed:@"blah"];
im = [im imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[[UIColor blackColor] setFill];
[im drawInRect:rect];

이 방법을 살펴보십시오

 + (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size;
    {
      UIImage *img = nil;

      CGRect rect = CGRectMake(0, 0, size.width, size.height);
      UIGraphicsBeginImageContext(rect.size);
      CGContextRef context = UIGraphicsGetCurrentContext();
      CGContextSetFillColorWithColor(context,
                                     color.CGColor);
      CGContextFillRect(context, rect);
      img = UIGraphicsGetImageFromCurrentImageContext();

      UIGraphicsEndImageContext();

      return img;
    }

Rpetrich의 솔루션 외에도 CGContextCliptomask 라인을 다음과 같이 교체 할 수도 있습니다.

    CGContextSetBlendMode(context, kCGBlendModeSourceIn); //this is the main bit!

GetCurrentContext의 모든 것에 의해 색상을 마스킹하는 작업을 수행하는 것은 Sourcein BlendMode입니다.

당신이 그것을하는 방법은 다음과 같습니다 스위프트 3.0 및 Uiimage에 확장을 사용합니다. 매우 간단합니다.

public extension UIImage {
    func filledImage(fillColor: UIColor) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)

        let context = UIGraphicsGetCurrentContext()!
        fillColor.setFill()

        context.translateBy(x: 0, y: self.size.height)
        context.scaleBy(x: 1.0, y: -1.0)

        context.setBlendMode(CGBlendMode.colorBurn)

        let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
        context.draw(self.cgImage!, in: rect)

        context.setBlendMode(CGBlendMode.sourceIn)
        context.addRect(rect)
        context.drawPath(using: CGPathDrawingMode.fill)

        let coloredImg : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        return coloredImg
    }
}

그런 다음 간단하게 실행하십시오.

let image = UIImage(named: "image_name").filledImage(fillColor: UIColor.red)

-set 블릿이 포함되지 않은 후속 드로잉 작업의 색상을 설정하는 데 사용됩니다. 나는 첫 번째 전화로 다른 전화로 다른 전화를 제안합니다 (빈) UIView 당신 위에 UIImageView 배경색 설정 :

myView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];

분명히 당신은 원하는 흰색과 알파 값을 사용해야합니다.

프로그래밍 방식으로 할 수 있습니다 스위프트 4.X 다음 방식으로 :

imageView.image = UIImage(named: "imageName")?.withRenderingMode(.alwaysTemplate)
imageView.tintColor = .purple
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top