Рисование прямоугольника в UIView - программирование
Подтвердить что ты не робот

Рисование прямоугольника в UIView

Я пытаюсь нарисовать прозрачный прямоугольник в моем UIView, который имеет черную границу.

Однако мой код создает полностью черный прямоугольник. Вот мой код:

- (void)drawRect:(CGRect)rect
{
    // Drawing code
    CGRect rectangle = CGRectMake(0, 100, 320, 100);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 0.5);
    CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 0.5);
    CGContextFillRect(context, rectangle);

}
4b9b3361

Ответ 1

- (void)drawRect:(CGRect)rect
{
    // Drawing code
    CGRect rectangle = CGRectMake(0, 100, 320, 100);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 0.0);   //this is the transparent color
    CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 0.5);
    CGContextFillRect(context, rectangle);
    CGContextStrokeRect(context, rectangle);    //this will draw the border

}

эффект подобен (backgroundColor синий)

enter image description here

Ответ 2

Он предоставит прямоугольник/квадрат, настроив значения self frame (индивидуальный вид или подкласс любого класса, который наследуется от UIView) с прозрачностью.

[self.layer setBorderWidth:1.0];
[self.layer setBorderColor:[[UIColor colorWithRed:0.10 green:0.45 blue:0.73 alpha:1.0] CGColor]];
[self.layer setCornerRadius:2.0];
[self.layer setShadowOffset:CGSizeMake(-2, -2)];
[self.layer setShadowColor:[[UIColor lightGrayColor] CGColor]];
[self.layer setShadowOpacity:0.5];

Ответ 3

Ваш код не требует вызова CGContextSetRGBFillColor и отсутствует вызов CGContextStrokeRect. В Swift 5 ваша окончательная реализация draw(_:) должна выглядеть так:

class CustomView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func draw(_ rect: CGRect) {
        guard let ctx = UIGraphicsGetCurrentContext() else { return }    
        ctx.setStrokeColor(red: 0, green: 0, blue: 0, alpha: 0.5)
        let rectangle = CGRect(x: 0, y: 100, width: 320, height: 100)
        ctx.stroke(rectangle)
    }

}

В качестве альтернативы, если вы действительно хотите вызвать CGContextSetRGBFillColor, вы также должны вызвать CGContextFillRect. Ваша финальная реализация draw(_:) будет выглядеть так со Swift 3:

class CustomView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func draw(_ rect: CGRect) {
        guard let ctx = UIGraphicsGetCurrentContext() else { return }

        ctx.setFillColor(red: 1, green: 1, blue: 1, alpha: 0)
        ctx.setStrokeColor(red: 0, green: 0, blue: 0, alpha: 0.5)

        let rectangle = CGRect(x: 0, y: 100, width: 320, height: 100)
        ctx.fill(rectangle)
        ctx.stroke(rectangle)
    }

}

Ответ 4

Один удобный отзыв......

Очень часто, когда вам нужно нарисовать квадрат

проще просто нарисовать "толстую полосу" .....

    let context = UIGraphicsGetCurrentContext()
    context!.setLineWidth(100)
    context!.setStrokeColor(blah.cgColor)
    context?.move(to: CGPoint(x: 500, y: 200))
    context?.addLine(to: CGPoint(x: 500, y: 300))
    context!.strokePath()

Это будет рисовать квадрат, который работает вниз от 200 до 300.

Он сосредоточен на 500 поперек и имеет ширину 100.

Ответ 5

CGRect  bounds  = connectorRect;
CGFloat minx = CGRectGetMinX(bounds), midx = CGRectGetMidX(bounds), maxx = CGRectGetMaxX(bounds);
CGFloat miny = CGRectGetMinY(bounds), maxy = CGRectGetMaxY(bounds);
CGContextSetFillColorWithColor(context, [UIColor grayColor].CGColor);
CGContextSetLineWidth(context, 1.0);
CGContextBeginPath(context);
CGContextSetStrokeColorWithColor(context,[UIColor clearColor].CGColor);
CGContextMoveToPoint(context, minx, maxy);
CGContextAddLineToPoint(context, midx, miny);
CGContextAddLineToPoint(context, maxx, maxy);
CGContextClosePath(context);
CGContextDrawPath(context, kCGPathFillStroke);