用颜色百分比填充矩形 - 目标C.

时间:2015-09-16 05:20:59

标签: objective-c

我用圆角动态创建了一个框。

我知道矩形的宽度和高度为300,我想要实现的是传递一个变量,它根据变量值填充颜色。

因此,如果变量值为10,颜色应该从Top填充,直到10ml。

enter image description here

这是更新的代码。

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    UIView *myBox  = [[UIView alloc] initWithFrame:CGRectMake(20,20, 300, 300)];
    myBox.layer.cornerRadius = 10;
    myBox.clipsToBounds = YES;
    myBox.backgroundColor = [UIColor blackColor];
   // [myBox addSubview:<#(UIView *)#>];
    [self drawRect:CGRectMake(0, 100, 300, 150)];
    [self.view addSubview:myBox];

}

- (void)drawRect:(CGRect)rect {
    self.view.backgroundColor = [UIColor cyanColor];
    float percentage = 0.5;
    float roundedOffPercentage = MIN(MAX(percentage, 0.0f), 1.0f);
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(CGRectGetMinX(rect), CGRectGetMaxY(rect), CGRectGetWidth(rect), CGRectGetHeight(rect)*roundedOffPercentage) cornerRadius:0];
    // draw the bezier path now
}

2 个答案:

答案 0 :(得分:1)

你可以继承UIView并覆盖它 - (void)drawRect:(CGRect)rect 并且喜欢以下内容。我希望它可以帮助你。

例如,通过重写UIView类来创建一个类TestView。

TestView.h

#import <UIKit/UIKit.h>
@interface TestView : UIView

@end

TestView.m

#import "TestView.h"

@implementation TestView

- (void)drawRect:(CGRect)rect 
{

    CGRect topRect = CGRectMake(0, 0, rect.size.width, rect.size.height/2.0);
    // Fill the rectangle with grey
    [[UIColor grayColor] setFill];
    UIRectFill( topRect );

    CGRect bottomRect = CGRectMake(0, rect.size.height/2.0, rect.size.width, rect.size.height/2.0);
    [[UIColor redColor] setFill];
    UIRectFill( bottomRect );
}

ViewController.m

#import "ViewController.h"
#import "TestView.h"

- (void)viewDidLoad {
    [super viewDidLoad];

    TestView *testView = [[TestView alloc] initWithFrame:CGRectMake(10, 10, 60, 60)];
    testView.backgroundColor = [UIColor greenColor];

    [self.view addSubview:testView];
}

如果您正在使用“界面”构建器,请确保将视图的类更改为YOUR_CUSTOM_VIEW_CLASS。您可以通过在界面生成器中选择视图并在检查器中选择“身份”窗格(最右侧的“i”图标)来执行此操作。

答案 1 :(得分:0)

子类//To display posts from either tag id 37 or 47, you could use tag as mentioned above, or explicitly specify by using tag__in: $query = new WP_Query( array( 'tag__in' => array( 37, 47 ) ) ); 并根据您需要的百分比自行绘制。

UIView