OC 不規則的UIButton點選效果

韋家冰發表於2017-12-13

####1、圖片型 需求:根據UIButton裡面的圖片,處理點選的效果,點選圖片的透明地方不需要響應事件。

OC  不規則的UIButton點選效果

解決思路:繼承UIButton,獲取點選點point對應的畫素點的顏色透明度來判斷(需要這個按鈕透明)。

實現程式碼: BBIrregularImageButton.h

@interface BBIrregularImageButton : UIButtonpublic methods.

@end
複製程式碼

BBIrregularImageButton.m

#import "BBIrregularImageButton.h"
#import "UIImage+ColorAtPixel.h"

@implementation BBIrregularImageButton

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    // 如果superResult = no(點選在bounds之外),直接返回NO,不處理
    BOOL response = [super pointInside:point withEvent:event];
    if (!response) {
        return response;
    }
    // 判斷設定有image
    if (self.currentImage || self.currentBackgroundImage) {
        // 重點
        response = [self isAlphaVisibleAtPoint:point];
    }
    return response;
}


/**
 截圖
 */
-(UIImage *)shotViewImage{
    
    UIImage *imageRet = [[UIImage alloc]init];
    UIGraphicsBeginImageContextWithOptions(self.frame.size, false, 0.0);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    imageRet = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return imageRet;
}


/**
 判斷點選點畫素的透明度
 */
- (BOOL)isAlphaVisibleAtPoint:(CGPoint)point
{
    UIImage *shotViewImage = [self shotViewImage];// 截圖button
    UIColor *pixelColor = [shotViewImage colorAtPixel:point];// 獲取圖片某一畫素點的顏色值,第三方
    CGFloat alpha = 0.0;
    [pixelColor getRed:NULL green:NULL blue:NULL alpha:&alpha];
    return alpha >= 0.1;
}


@end

複製程式碼

UIImage+ColorAtPixel.h

#import "UIImage+ColorAtPixel.h"

@implementation UIImage (ColorAtPixel)

//獲取圖片上某座標點對應的畫素的rgba值

- (UIColor *)colorAtPixel:(CGPoint)point{
    
    //如果圖片上不存在該點返回nil
    if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, self.size.width, self.size.height), point)) {
        return nil;
    }
    
    NSInteger pointX = truncl(point.x); //直接捨去小數,如1.58 -> 1.0
    NSInteger pointY= truncl(point.y);
    
    CGImageRef cgImage = self.CGImage;
    NSUInteger width = self.size.width;
    NSUInteger height = self.size.height;
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); //bitmap上下文使用的顏色空間
    
    int bytesPerPixel = 4; //bitmap在記憶體中所佔的位元數
    int bytesPerRow = bytesPerPixel * 1; //bitmap的每一行在記憶體所佔的位元數
    NSUInteger bitsPerComponent = 8; //記憶體中畫素的每個元件的位數.例如,對於32位畫素格式和RGB 顏色空間,你應該將這個值設為8.
    unsigned char pixelData[4] = {0, 0, 0, 0}; //初始化畫素資訊
    
    //建立點陣圖檔案環境。點陣圖檔案可自行百度 bitmap
    CGContextRef context = CGBitmapContextCreate(pixelData,
                                                 1,
                                                 1,
                                                 bitsPerComponent,
                                                 bytesPerRow,
                                                 colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); //指定bitmap是否包含alpha通道,畫素中alpha通道的相對位置,畫素元件是整形還是浮點型等資訊的字串。
    CGColorSpaceRelease(colorSpace);
    CGContextSetBlendMode(context, kCGBlendModeCopy); //當一個顏色覆蓋上另外一個顏色,兩個顏色的混合方式
    CGContextTranslateCTM(context, -pointX, pointY - (CGFloat)height); //改變畫布位置
    CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, (CGFloat)width, (CGFloat)height ), cgImage); //繪製圖片
    CGContextRelease(context);
    
    
    CGFloat red = (CGFloat)pixelData[0] / 255.0f;
    CGFloat green = (CGFloat)pixelData[1] / 255.0f;
    CGFloat blue = (CGFloat)pixelData[2] / 255.0f;
    CGFloat alpha = (CGFloat)pixelData[3] / 255.0f;
    
    UIColor *pointColor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
    return pointColor;
}

@end
複製程式碼

####2、自畫型

OC  不規則的UIButton點選效果

實現程式碼:

BBShapedButton.h

#import "BBShapedButton.h"

@implementation BBShapedButton

//繪製按鈕時新增path遮罩
- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    CAShapeLayer *shapLayer = [CAShapeLayer layer];
    shapLayer.path = self.path.CGPath;
    self.layer.mask = shapLayer;
}

//覆蓋方法,點選時判斷點是否在path內,YES則響應,NO則不響應
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    // 判斷父類能不能響應點選
    BOOL res = [super pointInside:point withEvent:event];
    if (res){
        // 再判斷點選是不是在path內
        res = [self.path containsPoint:point];
    }
    return res;
}
@end
複製程式碼

使用例子

    BBShapedButton *btn = [BBShapedButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(50, 50, 200, 100);
    
    // 設定UIBezierPath
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(0, 100)];
    [path addLineToPoint:CGPointMake(20, 0)];
    [path addLineToPoint:CGPointMake(45, 50)];
    [path addLineToPoint:CGPointMake(70, 0)];
    [path addLineToPoint:CGPointMake(150, 30)];
    [path addLineToPoint:CGPointMake(175, 0)];
    [path addLineToPoint:CGPointMake(200, 100)];
    [path closePath];
    btn.path = path;
    
    [btn setTitle:@"按鈕" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    btn.backgroundColor = [UIColor greenColor];
    [self.view addSubview:btn];
複製程式碼

下載demo

相關文章