【问题标题】:No resizing, but positioning when setting backgroundImage of UIButton设置 UIButton 的 backgroundImage 时不调整大小,但定位
【发布时间】:2013-08-02 02:41:12
【问题描述】:

我希望按钮基本上与原始图片的某个部分重叠并裁剪其余部分,而不是将图片挤压到按钮中。我似乎找不到 UIContentMode 来实现这一点。

【问题讨论】:

    标签: ios uibutton uiimage


    【解决方案1】:

    试试这个:

    您可以在任何 UIView 中的某个 CGRect 之后拥有一个 UIImage。只需使用包含原始 UIImage 的 UIImageView 部分制作一个 CGRect,然后执行以下代码:

     CGRect newImageFrame = CGRectMake(...); //fill this rect according to the crop area of the imageView
     UIGraphicsBeginImageContextWithOptions(newImageFrame, YES, 0);
     [editingCell.layer renderInContext:UIGraphicsGetCurrentContext()];
     UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
     UIGraphicsEndImageContext();
    

    现在newImage 将保存您将用作按钮背景的图像。

    示例: 假设您的 UIImageView 具有框架 (50,50, 100, 200),您可以使用以下内容裁剪图像的类似结果:newImageFrame = CGRectMake(50, 130, 100, 40)。

    请告诉我是否有效。

    【讨论】:

      【解决方案2】:

      请试试这个代码:

      CGRect frame = CGRectMake(10, y, 280, 40);
              UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
              button.frame = frame;
              button.tag=i;
              [button setTitle:(NSString *)@"new button" forState:(UIControlState)UIControlStateNormal];
              [button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
              [button setBackgroundImage:[UIImage imageNamed:@"temp.png"] forState:UIControlStateNormal];
              [self.view addSubview:button];
      

      我已经检查过了。

      希望这会对你有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-29
        • 1970-01-01
        • 2021-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多