How to get the pixel color on touch?

后端 未结 5 2140
闹比i
闹比i 2020-11-27 02:28

I know this is a common question and there are a lot of answers of this question. I\'ve used some of this. Although many of them are the same. But the sad thing for me is th

5条回答
  •  抹茶落季
    2020-11-27 03:09

    First, I'd like to thank the author of this code, it helped me a lot for my game project, as I was looking for this function to do a pixel-perfect hitbox (excluding where the aplha is O). Here's a little update for Swift 5:

    // Fonction permettant de retourner les valeurs RGBA d'un pixel d'une vue
    func getPixelColor(atPosition:CGPoint) -> UIColor{
    
        var pixel:[CUnsignedChar] = [0, 0, 0, 0];
        let colorSpace = CGColorSpaceCreateDeviceRGB();
        let bitmapInfo = CGBitmapInfo(rawValue:    CGImageAlphaInfo.premultipliedLast.rawValue);
        let context = CGContext(data: &pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: bitmapInfo.rawValue);
    
        context!.translateBy(x: -atPosition.x, y: -atPosition.y);
        layer.render(in: context!);
        let color:UIColor = UIColor(red: CGFloat(pixel[0])/255.0,
                                    green: CGFloat(pixel[1])/255.0,
                                    blue: CGFloat(pixel[2])/255.0,
                                    alpha: CGFloat(pixel[3])/255.0);
    
        return color;
    
    }
    

    I had somme issues with pixel.dealloc(4), as in Swift 5 it seems that you can't dealloc with capacity parameter anymore. I removed the (4), but it had some weird behavior (as the dealloc() didn't dealloc the whole array).

    I didn't do an extension of UIView as in my project I have my own subclass, but this can be easily done.

    The way I implement the code:

    // Méthode déterminant si le "touch" est validé par l'objet (par défaut, exclut les zones transparentes et les objets invisibles). A surcharger si nécessaire.
    func isHit(atPosition position:CGPoint) -> Bool
    {
    
        // Si l'objet n'est pas caché (paramètre isHidden) et si la zone touchée correspond à une zone effectivement dessinée (non transparente), retourne true.
        if (!self.isHidden && self.getPixelColor(atPosition: position).cgColor.alpha != 0) {return true}
        else {return false}
    
    }
    

    I hope this can help.

提交回复
热议问题