Подтвердить что ты не робот

Добавление фонового изображения в UILabel

Как добавить фоновое изображение в UILabel в приложении iPhone. Я пытался сделать это через IB, но без результата.

4b9b3361

Ответ 1

Попробуйте сделать это с кодом:

Objective-C:

theLabel.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"blah"]];

Swift:

theLabel.backgroundColor = UIColor(patternImage: UIImage(named: "blah")!)

Или поместите UIImageView за метку (не рекомендуется).


Обновление: размещение UIImageView позади метки не рекомендуется, потому что тогда вам придется управлять двумя видами. Но если вы должны сделать то, что может сделать только UIImageView, это хороший подход. Я подозреваю, что ваше приложение будет работать таким образом.

Ответ 2

если вы хотите, чтобы изображение было растянуто для заполнения ширины метки. попробуйте этот код.

UILabel *myLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 20)];

UIImage *img = [UIImage imageNamed:@"a.png"];
CGSize imgSize = myLabel.frame.size;

UIGraphicsBeginImageContext( imgSize );
[img drawInRect:CGRectMake(0,0,imgSize.width,imgSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

myLabel.backgroundColor = [UIColor colorWithPatternImage:newImage];

Ответ 3

Swift 2.2: установите фоновое изображение с цветом фона

    UIGraphicsBeginImageContextWithOptions(stationNameLabel.frame.size, false, 0.0)

    let context = UIGraphicsGetCurrentContext();

    let components = CGColorGetComponents(color.CGColor)

    CGContextSetRGBFillColor(context, components[0], components[1], components[2], 0.4);
    CGContextFillRect(context, CGRectMake(0.0, 0.0, stationNameLabel.frame.size.width, stationNameLabel.frame.size.height));


    targetImage.drawInRect(CGRectMake(0.0, 0.0, stationNameLabel.frame.size.width, stationNameLabel.frame.size.height))
    let resultImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    label.backgroundColor = UIColor(patternImage: resultImage)

Ответ 4

 let messageBackgroundView = UIImageView()
        messageBackgroundView.image = UIImage(named: "chat-background")
        if messageBackgroundView.superview != lblChatdata.superview {
            lblChatdata.superview!.insertSubview(messageBackgroundView, belowSubview: lblChatdata)
            messageBackgroundView.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                messageBackgroundView.leadingAnchor.constraint(equalTo: lblChatdata.leadingAnchor),
                messageBackgroundView.trailingAnchor.constraint(equalTo: lblChatdata.trailingAnchor),
                messageBackgroundView.topAnchor.constraint(equalTo: lblChatdata.topAnchor),
                messageBackgroundView.bottomAnchor.constraint(equalTo: lblChatdata.bottomAnchor),
                ])
            messageBackgroundView.contentMode = .scaleAspectFill
        }

Ответ 5

@pixelfreak, ваше право. Экземпляр UIColor с шаблоном цветного изображения имеет серьезные проблемы с производительностью при назначении его backroundcolor

cell.cellLabel.backgroundColor = UIColor(patternImage: UIImage(named: "background")!)