How to get pixel color at location from UIimage scaled within a UIimageView

前端 未结 3 1516
悲哀的现实
悲哀的现实 2020-12-20 01:23

I\'m currently using this technique to get the color of a pixel in a UIimage. (on Ios)

- (UIColor*) getPixelColorAtLocation:(CGPoint)point {
UIColor* color =         


        
相关标签:
3条回答
  • 2020-12-20 01:42

    Here's a pointer:

    0x3A28213A //sorry, I couldn't resist the joke
    

    For real now: after going through the comments on the page at markj.net, a certain James has suggested to make the following changes:

    size_t w = CGImageGetWidth(inImage); //Written by Mark
    size_t h = CGImageGetHeight(inImage); //Written by Mark
    float xscale = w / self.frame.size.width;
    float yscale = h / self.frame.size.height;
    point.x = point.x * xscale;
    point.y = point.y * yscale;
    

    (thanks to http://www.markj.net/iphone-uiimage-pixel-color/comment-page-1/#comment-2159)

    This didn't actually work for me... Not that I did much testing, and I'm not the world's greatest programmer (yet)...

    My solution was to scale the UIImageView in such a way that each pixel of the image in it was the same size as a standard CGPoint on the screen, then I took my color like normal (using getPixelColorAtLocation:(CGPoint)point) , then I scaled the image back to the size I wanted.

    Hope this helps!

    0 讨论(0)
  • 2020-12-20 01:43

    try this for swift3

    func getPixelColor(image: UIImage, x: Int, y: Int, width: CGFloat) -> UIColor 
    {
    
        let pixelData = CGDataProviderCopyData(CGImageGetDataProvider(image.CGImage))
        let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
    
        let pixelInfo: Int = ((Int(width) * y) + x) * 4
    
        let r = CGFloat(data[pixelInfo]) / CGFloat(255.0)
        let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0)
        let b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0)
        let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0)
    
        return UIColor(red: r, green: g, blue: b, alpha: a)
    }
    
    0 讨论(0)
  • 2020-12-20 01:58

    Use the UIImageView Layer:

    - (UIColor*) getPixelColorAtLocation:(CGPoint)point {
        UIColor* color = nil;
    
        UIGraphicsBeginImageContext(self.frame.size);
        CGContextRef cgctx = UIGraphicsGetCurrentContext();
        if (cgctx == NULL) { return nil; /* error */ }
    
        [self.layer renderInContext:cgctx];
    
        unsigned char* data = CGBitmapContextGetData (cgctx);
        /*
        ...
        */
        UIGraphicsEndImageContext();
        return color;
    }
    
    0 讨论(0)
提交回复
热议问题