美文网首页
[iOS]点击UIImageView获取点击处颜色

[iOS]点击UIImageView获取点击处颜色

作者: PlutoMa | 来源:发表于2016-10-18 16:36 被阅读182次

    最近在一个项目中,需要实现这么一个效果:显示一张地图,通过点击不同位置,来切换点击处的行政区域,效果图如下:

    map.gif

    在此记录一下实现思路:

    • 1.首先要有一组需要展示的不同地区的图片,我的图片如下:
    maps.png

    这里要注意,要留意map_whs这张图片的尺寸,因为代码中需要使用到这个尺寸。

    • 2.然后,你需要知道每个地区所对应的地图颜色,我的地图对于颜色如下:
    colors.png

    我自己写了个JSON文件,用来保存对应的颜色、名称以及图片名称。

    • 3.在代码中,创建一个UIImageView,这个UIImageView的宽高比例要与刚才提到的map_whs图片的宽高比例一致,同时,计算出UIImageView的宽(或者高)与map_whs的宽(或者高)德比例,然后为UIImageView添加点击事件:
        self.mapImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.nameLabel.plt_y + self.nameLabel.plt_height, self.view.plt_width, self.view.plt_width / (kMapImageWidth / kMapImageHeight))];
        UITapGestureRecognizer *mapImageViewTGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(mapImageViewTGRAction:)];
        [self.mapImageView addGestureRecognizer:mapImageViewTGR];
        self.mapImageView.userInteractionEnabled = YES;
        [self.view addSubview:self.mapImageView];
    
    • 4.处理点击事件,获取到的点击位置,要根据上一步计算的比例来对应到map_whs这张图片的点上:
    - (void)mapImageViewTGRAction:(UITapGestureRecognizer *)tgr
    {
        //触点位置
        CGPoint touchLocation = [tgr locationInView:self.mapImageView];
        
        if (touchLocation.x > 0 && touchLocation.x <= self.mapImageView.plt_width && touchLocation.y > 0 && touchLocation.y <= self.mapImageView.plt_height) {
            //触点颜色
            UIColor *positionColor=[self getColor:touchLocation];
            for (NSDictionary *dic in self.txtArr) {
                UIColor *color = PltColorWithHEX(dic[kMapTxtColor]);
                if (CGColorEqualToColor(color.CGColor, positionColor.CGColor)) {
                    [self setUpImage:dic];
                    break;
                }
            }
        }
    }
    
    #pragma mark - 获取点击颜色
    - (UIColor *)getColor:(CGPoint)point
    {
        UIColor* color = [UIColor whiteColor];
        if (point.x > 0 && point.y > 0) {
            
            CGFloat ratio = kMapImageWidth / self.mapImageView.plt_width;
            
            CGPoint realPoint = CGPointMake(point.x * ratio, point.y * ratio);
            CGImageRef inImage = [UIImage imageNamed:@"map_whs"].CGImage;
            CGContextRef cgctx = [self createARGBBitmapContextFromImage:inImage];
            if (cgctx == NULL) {
                return nil;
            }
            size_t w = CGImageGetWidth(inImage);
            size_t h = CGImageGetHeight(inImage);
            CGRect rect = {{0,0},{w,h}};
            
            // Draw the image to the bitmap context. Once we draw, the memory
            // allocated for the context for rendering will then contain the
            // raw image data in the specified color space.
            CGContextDrawImage(cgctx, rect, inImage);
            
            // Now we can get a pointer to the image data associated with the bitmap
            // context.
            unsigned char* data = CGBitmapContextGetData (cgctx);
            if (data != NULL)
            {
                //offset locates the pixel in the data from x,y.
                //4 for 4 bytes of data per pixel, w is width of one row of data.
                @try
                {
                    int offset = 4*((w*round(realPoint.y))+round(realPoint.x));
                    //NSLog(@"offset: %d", offset);
                    int alpha =  data[offset];
                    int red = data[offset+1];
                    int green = data[offset+2];
                    int blue = data[offset+3];
                    //            NSLog(@"offset: %i colors: RGB A %i %i %i  %i",offset,red,green,blue,alpha);
                    color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:(blue/255.0f) alpha:(alpha/255.0f)];
                }
                @catch (NSException * e)
                {
                    NSLog(@"%@",[e reason]);
                }
                @finally
                {
                    
                }
                
            }
            
            // When finished, release the context
            CGContextRelease(cgctx);
            // Free image data memory for the context
            if (data)
            {
                free(data);
            }
            
        }
        return color;
    }
    
    - (CGContextRef) createARGBBitmapContextFromImage:(CGImageRef) inImage
    {
        
        CGContextRef    context = NULL;
        CGColorSpaceRef colorSpace;
        void *          bitmapData;
        int             bitmapByteCount;
        int             bitmapBytesPerRow;
        
        // Get image width, height. We'll use the entire image.
        size_t pixelsWide = CGImageGetWidth(inImage);
        size_t pixelsHigh = CGImageGetHeight(inImage);
        
        // Declare the number of bytes per row. Each pixel in the bitmap in this
        // example is represented by 4 bytes; 8 bits each of red, green, blue, and
        // alpha.
        bitmapBytesPerRow   = (int)(pixelsWide * 4);
        bitmapByteCount     =(int)(bitmapBytesPerRow * pixelsHigh);
        
        // Use the generic RGB color space.
        colorSpace = CGColorSpaceCreateDeviceRGB();
        
        if (colorSpace == NULL)
        {
            fprintf(stderr, "Error allocating color space\n");
            return NULL;
        }
        
        // Allocate memory for image data. This is the destination in memory
        // where any drawing to the bitmap context will be rendered.
        bitmapData = malloc( bitmapByteCount );
        if (bitmapData == NULL)
        {
            fprintf (stderr, "Memory not allocated!");
            CGColorSpaceRelease( colorSpace );
            return NULL;
        }
        
        // Create the bitmap context. We want pre-multiplied ARGB, 8-bits
        // per component. Regardless of what the source image format is
        // (CMYK, Grayscale, and so on) it will be converted over to the format
        // specified here by CGBitmapContextCreate.
        context = CGBitmapContextCreate (bitmapData,
                                         pixelsWide,
                                         pixelsHigh,
                                         8,      // bits per component
                                         bitmapBytesPerRow,
                                         colorSpace,
                                         kCGImageAlphaPremultipliedFirst);
        if (context == NULL)
        {
            free (bitmapData);
            fprintf (stderr, "Context not created!");
        }
        // Make sure and release colorspace before returning
        CGColorSpaceRelease( colorSpace );
        return context;
    }
    

    Demo地址,TouchColor-Demo文件夹

    相关文章

      网友评论

          本文标题:[iOS]点击UIImageView获取点击处颜色

          本文链接:https://www.haomeiwen.com/subject/mvrtuttx.html