【问题标题】:Set background - centered and not stretched设置背景 - 居中且不拉伸
【发布时间】:2023-03-29 15:20:02
【问题描述】:

程序通过以下方式将背景设置为图像:

 [backgroundViewProxy setBackgroundColor:[UIColor colorWithPatternImage:[theme backgroundImage]]];

对应UIView的drawRect为:

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGSize phase = self.backgroundShift; //set this property to affect the positioning of the background image
    CGContextSetPatternPhase(context, phase);

    CGColorRef color = self.backgroundColor.CGColor;
    CGContextSetFillColorWithColor(context, color);
    CGContextFillRect(context, self.bounds);
    CGContextRestoreGState(context);
}

代码不是我自己写的。我必须修改它。 我明白这里发生了什么,但我找不到解决这个问题的方法:

我希望图像在屏幕上居中(具有和高度),并且不应拉伸或重复。

此时,图像会重复以填满屏幕。 我在互联网上进行了搜索,但没有找到一个明确的解决方案,可以在类似的上下文中将图像居中(或定位)。

如果有人可以提供帮助,我会很高兴。

【问题讨论】:

    标签: ios image layout


    【解决方案1】:

    来自苹果的文档:

    + (UIColor *)colorWithPatternImage:(UIImage *)image
    

    您可以使用图案颜色来设置填充或描边颜色,就像设置纯色一样。在绘制过程中,图案颜色的图像会根据需要平铺以覆盖给定区域。

    另一种方法是将 view.layer.contents 设置为您的图像,方法是将其转换为类型 (id)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-12
      • 2016-06-06
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多