[iOS]點(diǎn)擊UIImageView獲取點(diǎn)擊處顏色

最近在一個(gè)項(xiàng)目中,需要實(shí)現(xiàn)這么一個(gè)效果:顯示一張地圖,通過(guò)點(diǎn)擊不同位置,來(lái)切換點(diǎn)擊處的行政區(qū)域,效果圖如下:

map.gif

在此記錄一下實(shí)現(xiàn)思路:

  • 1.首先要有一組需要展示的不同地區(qū)的圖片,我的圖片如下:
maps.png

這里要注意,要留意map_whs這張圖片的尺寸,因?yàn)榇a中需要使用到這個(gè)尺寸。

  • 2.然后,你需要知道每個(gè)地區(qū)所對(duì)應(yīng)的地圖顏色,我的地圖對(duì)于顏色如下:
colors.png

我自己寫(xiě)了個(gè)JSON文件,用來(lái)保存對(duì)應(yīng)的顏色、名稱(chēng)以及圖片名稱(chēng)。

  • 3.在代碼中,創(chuàng)建一個(gè)UIImageView,這個(gè)UIImageView的寬高比例要與剛才提到的map_whs圖片的寬高比例一致,同時(shí),計(jì)算出UIImageView的寬(或者高)與map_whs的寬(或者高)德比例,然后為UIImageView添加點(diǎn)擊事件:
    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.處理點(diǎn)擊事件,獲取到的點(diǎn)擊位置,要根據(jù)上一步計(jì)算的比例來(lái)對(duì)應(yīng)到map_whs這張圖片的點(diǎn)上:
- (void)mapImageViewTGRAction:(UITapGestureRecognizer *)tgr
{
    //觸點(diǎn)位置
    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) {
        //觸點(diǎn)顏色
        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 - 獲取點(diǎn)擊顏色
- (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文件夾

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容