0

Доброго вечера всем! Подскажите пожалуйста как можно вырезать область в UIView, чтобы эта область была прозрачной? Нашел, что можно как-то через маску, но всё же не понял как это сделать, не получается с реализацией.

Наложить слой с цветом фона не вариант, т.к. фон градиент.

1 ответ 1

1

Создайте сабкласс UIView таким образом:

Header (.h) file:

#import <UIKit/UIKit.h>

@interface TranparentView : UIView

- (id)initWithFrame:(CGRect)frame 
    backgroundColor:(UIColor*)color 
   transparentRects:(NSArray*)rects 
             circle:(BOOL)circle;

Implementation (.m) file:

#import "TranparentView.h"

@implementation TranparentView {
    NSArray *rectsArray;
    UIColor *backgroundColor;
    BOOL isCircle;
}


- (id)initWithFrame:(CGRect)frame 
    backgroundColor:(UIColor*)color 
   transparentRects:(NSArray*)rects 
             circle:(BOOL)circle {

    backgroundColor = color;
    rectsArray = rects;
    isCircle = circle;
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.opaque = NO;
    }
    return self;
}


- (void)drawRect:(CGRect)rect {

    [backgroundColor setFill];
    UIRectFill(rect);

    for (NSValue *holeRectValue in rectsArray) {
        CGRect holeRect = [holeRectValue CGRectValue];
        CGRect holeRectIntersection = CGRectIntersection( holeRect, rect );

        if (isCircle) {
            CGContextRef context = UIGraphicsGetCurrentContext();

            if( CGRectIntersectsRect( holeRectIntersection, rect ) )
            {
                CGContextAddEllipseInRect(context, holeRectIntersection);
                CGContextClip(context);
                CGContextClearRect(context, holeRectIntersection);
                CGContextSetFillColorWithColor( context, [UIColor clearColor].CGColor );
                CGContextFillRect( context, holeRectIntersection);
            }
        } else {
            [[UIColor clearColor] setFill];
            UIRectFill(holeRectIntersection);
        }
    }
}

И в Вашем контроллере, например, создаете TranparentView с настройками:

backgroundColor - цвет вью;

transparentRects - массив рамок;

circle(BOOL) - yes - круг/овал, no - квадрат/прямоугольник.

так:

NSArray *transparentRects = @[[NSValue valueWithCGRect:CGRectMake(20, 20, 60, 50)]];

TransparentView *transparentView = [[TransparentView alloc] initWithFrame:CGRectMake(0, 0, 100, 100) backgroundColor:[UIColor greenColor] transparentRects:transparentRects circle:NO];

[self.view addSubview:transparentView];

Вы можете вырезать как круглую область, так и квадратную. Код можно улучшить под Ваши нужды. Надеюсь это Вам поможет.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.