Css properties progress

This commit is contained in:
vakrilov
2015-07-02 18:59:51 +03:00
parent de4ede5c8b
commit d74d9b8fbb
20 changed files with 849 additions and 302 deletions

View File

@ -241,6 +241,7 @@
<TypeScriptCompile Include="image-source\image-source.ios.ts">
<DependentUpon>image-source.d.ts</DependentUpon>
</TypeScriptCompile>
<TypeScriptCompile Include="js-libs\reworkcss-value\reworkcss-value.d.ts" />
<TypeScriptCompile Include="platform\platform.ios.ts">
<DependentUpon>platform.d.ts</DependentUpon>
</TypeScriptCompile>
@ -454,6 +455,16 @@
<TypeScriptCompile Include="ui\layouts\wrap-layout\wrap-layout.ts">
<DependentUpon>wrap-layout.d.ts</DependentUpon>
</TypeScriptCompile>
<TypeScriptCompile Include="ui\styling\background-common.ts">
<DependentUpon>background.d.ts</DependentUpon>
</TypeScriptCompile>
<TypeScriptCompile Include="ui\styling\background.ios.ts">
<DependentUpon>background.d.ts</DependentUpon>
</TypeScriptCompile>
<TypeScriptCompile Include="ui\styling\background.d.ts" />
<TypeScriptCompile Include="ui\styling\background.android.ts">
<DependentUpon>background.d.ts</DependentUpon>
</TypeScriptCompile>
<TypeScriptCompile Include="ui\styling\css-selector.d.ts" />
<TypeScriptCompile Include="ui\styling\css-selector.ts">
<DependentUpon>css-selector.d.ts</DependentUpon>
@ -699,6 +710,7 @@
<Content Include="apps\ui-tests-app\pages\text\text-view.xml" />
<Content Include="apps\ui-tests-app\pages\text\label.xml" />
<Content Include="apps\ui-tests-app\pages\text\button.xml" />
<Content Include="js-libs\reworkcss-value\reworkcss-value.js" />
<Content Include="ui\layouts\stack-layout\package.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
@ -1588,6 +1600,9 @@
<Content Include="ui\repeater\package.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="js-libs\reworkcss-value\LICENSE" />
<Content Include="js-libs\reworkcss-value\package.json" />
<Content Include="js-libs\reworkcss-value\Readme.md" />
</ItemGroup>
<ItemGroup>
<None Include="build\tslint.json" />

View File

@ -1,8 +1,15 @@
import observable = require("data/observable");
import pages = require("ui/page");
var vm = new observable.Observable();
// Event handler for Page "loaded" event attached in main-page.xml
export function pageLoaded(args: observable.EventData) {
vm.set("style", "background-image: url('~/tests/pages/test2.png'); \nborder-color: green; \nborder-radius: 20; \nborder-width: 4;");
// Get the event sender
var page = <pages.Page>args.object;
page.bindingContext = vm;
}
export function applyTap(args){
args.object.parent.style = vm.get("style");
}

View File

@ -1,5 +1,6 @@
<Page>
<GridLayout style="background-image: url('~/pages/test2.png'); border-color: green; border-radius: 20; border-width: 4;">
<Button text="just a button" horizontalAlignment="center" verticalAlignment="center"/>
<Page loaded="pageLoaded">
<GridLayout style="background-image: url('~/pages/test2.png'); border-color: green; border-radius: 20; border-width: 4;" rows="*, auto">
<TextView text="{{ style }}" />
<Button text="apply" horizontalAlignment="center" verticalAlignment="center" tap="applyTap" row="1"/>
</GridLayout>
</Page>

View File

@ -22,7 +22,7 @@ export function test_css_dataURI_is_applied_to_backgroundImageSource() {
var page = <pageModule.Page>views[1];
page.css = "StackLayout { background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD///l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC;') }";
var value = stack.style._getValue(styleModule.backgroundImageSourceProperty);
var value = undefined; //stack.style._getValue(styleModule.backgroundImageSourceProperty);
TKUnit.assert(value !== undefined, "Style background-image not loaded correctly from data URI.");
});

View File

@ -0,0 +1,9 @@
(The MIT License)
Copyright (c) 2013 TJ Holowaychuk <tj@vision-media.ca>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,45 @@
# css-value
WIP CSS value parser
## Example
The CSS value string "1px 0 0 5% .5px .10 1.5" yields:
```js
[
{ type: 'number', string: '1px', unit: 'px', value: 1 },
{ type: 'number', string: '0', unit: '', value: 0 },
{ type: 'number', string: '0', unit: '', value: 0 },
{ type: 'number', string: '5%', unit: '%', value: 5 },
{ type: 'number', string: '.5px', unit: 'px', value: .5 },
{ type: 'number', string: '.10', unit: '', value: .1 },
{ type: 'number', string: '1.5', unit: '', value: 1.5 }
]
```
## License
(The MIT License)
Copyright (c) 2013 TJ Holowaychuk &lt;tj@vision-media.ca&gt;
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,12 @@
{
"name": "reworkcss-value.js",
"version": "0.0.1",
"description": "CSS value parser",
"keywords": ["css", "parser", "value"],
"author": "TJ Holowaychuk <tj@vision-media.ca>",
"repository": {
"type": "git",
"url": "git://github.com/visionmedia/css-value.git"
},
"main": "reworkcss-value.js"
}

View File

@ -0,0 +1,10 @@
declare module "js-libs/reworkcss-value" {
export interface CSSValue {
type: string;
string: string;
unit: string;
value: number;
}
export function parse(cssValue: string): Array<CSSValue>;
}

View File

@ -0,0 +1,113 @@
module.exports.parse = parse;
function parse(str) {
return new Parser(str).parse();
}
function Parser(str) {
this.str = str;
}
Parser.prototype.skip = function(m){
this.str = this.str.slice(m[0].length);
};
Parser.prototype.comma = function(){
var m = /^, */.exec(this.str);
if (!m) return;
this.skip(m);
return { type: 'comma', string: ',' };
};
Parser.prototype.ident = function(){
var m = /^([\w-]+) */.exec(this.str);
if (!m) return;
this.skip(m);
return {
type: 'ident',
string: m[1]
}
};
Parser.prototype.int = function(){
var m = /^((\d+)(\S+)?) */.exec(this.str);
if (!m) return;
this.skip(m);
var n = ~~m[2];
var u = m[3];
return {
type: 'number',
string: m[1],
unit: u || '',
value: n
}
};
Parser.prototype.float = function(){
var m = /^(((?:\d+)?\.\d+)(\S+)?) */.exec(this.str);
if (!m) return;
this.skip(m);
var n = parseFloat(m[2]);
var u = m[3];
return {
type: 'number',
string: m[1],
unit: u || '',
value: n
}
};
Parser.prototype.number = function(){
return this.float() || this.int();
};
Parser.prototype.double = function(){
var m = /^"([^"]*)" */.exec(this.str);
if (!m) return m;
this.skip(m);
return {
type: 'string',
quote: '"',
string: '"' + m[1] + '"',
value: m[1]
}
};
Parser.prototype.single = function(){
var m = /^'([^']*)' */.exec(this.str);
if (!m) return m;
this.skip(m);
return {
type: 'string',
quote: "'",
string: "'" + m[1] + "'",
value: m[1]
}
};
Parser.prototype.string = function(){
return this.single() || this.double();
};
Parser.prototype.value = function(){
return this.number()
|| this.ident()
|| this.string()
|| this.comma();
};
Parser.prototype.parse = function(){
var vals = [];
while (this.str.length) {
var obj = this.value();
if (!obj) throw new Error('failed to parse near `' + this.str.slice(0, 10) + '...`');
vals.push(obj);
}
return vals;
};

View File

@ -3,7 +3,7 @@ import trace = require("trace");
import utils = require("utils/utils");
import dependencyObservable = require("ui/core/dependency-observable");
import proxy = require("ui/core/proxy");
import style = require("ui/styling/style");
import background = require("ui/styling/background");
// merge the exports of the common file with the exports of this file
declare var exports;
@ -207,57 +207,11 @@ export class View extends viewCommon.View {
}
private _onBoundsChanged() {
var nativeView: UIView = <UIView>this._nativeView;
var imageSource = this.style._getValue(style.backgroundImageSourceProperty);
if (imageSource && imageSource.ios) {
var img = <UIImage>imageSource.ios;
var frame = nativeView.frame;
console.log("Frame: " + NSStringFromCGRect(frame));
console.log("ImageSize: " + NSStringFromCGSize(img.size));
if (frame.size.width > 0 && frame.size.height) {
var repeatX = false;
var repeatY = false;
var posX = 15;
var posY = 35;
var sizeX = 15;
var sizeY = 40;
if (sizeX > 0 && sizeY > 0) {
var resizeRect = CGRectMake(0, 0, sizeX, sizeY);
UIGraphicsBeginImageContext(resizeRect.size);
img.drawInRect(resizeRect);
img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
UIGraphicsBeginImageContextWithOptions(frame.size, false, 1.0);
if (!repeatX && !repeatY) {
img.drawAtPoint(CGPointMake(posX, posY));
}
else {
var w = repeatX ? frame.size.width : img.size.width;
var h = repeatY ? frame.size.height : img.size.height;
var context = UIGraphicsGetCurrentContext();
CGContextSetPatternPhase(context, CGSizeMake(posX, posY));
console.log("context" + context);
posX = repeatX ? 0 : posX;
posY = repeatY ? 0 : posY;
var patternRect = CGRectMake(posX, posY, w, h);
console.log("patternRect: " + NSStringFromCGRect(patternRect));
img.drawAsPatternInRect(patternRect);
}
var bkgImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
console.log("bkgImage.size: " + NSStringFromCGSize(bkgImage.size));
nativeView.backgroundColor = UIColor.alloc().initWithPatternImage(bkgImage);
}
var bgColor = background.ios.createBackgroundUIColor(this);
if (bgColor) {
this._nativeView.backgroundColor = bgColor;
}
}
}
export class CustomLayoutView extends View {

10
ui/enums/enums.d.ts vendored
View File

@ -402,4 +402,14 @@
export var bold: string;
}
/**
* Specifies nackground repeat.
*/
export module BackgroundRepeat {
export var repeat: string;
export var repeatX: string;
export var repeatY: string;
export var noRepeat: string;
}
}

View File

@ -113,3 +113,10 @@ export module FontWeight {
export var normal: string = "normal";
export var bold: string = "bold";
}
export module BackgroundRepeat {
export var repeat: string = "repeat";
export var repeatX: string = "repeat-x";
export var repeatY: string = "repeat-y";
export var noRepeat: string = "no-repeat";
}

View File

@ -0,0 +1,195 @@
import imageSource = require("image-source");
import colorModule = require("color");
import viewModule = require("ui/core/view");
import style = require("ui/styling/style");
import types = require("utils/types");
import view = require("ui/core/view");
import enums = require("ui/enums");
import utils = require("utils/utils");
import dts = require("ui/styling/background");
import cssValue = require("js-libs/reworkcss-value");
export class Background implements dts.Background {
public static default = new Background(undefined, undefined, undefined, undefined, undefined);
color: colorModule.Color;
image: imageSource.ImageSource;
repeat: string;
position: string;
size: string;
constructor(
color: colorModule.Color,
image: imageSource.ImageSource,
repeat: string,
position: string,
size: string) {
this.color = color;
this.image = image;
this.repeat = repeat;
this.position = position;
this.size = size;
}
public withColor(value: colorModule.Color): Background {
return new Background(value, this.image, this.repeat, this.position, this.size);
}
public withImage(value: imageSource.ImageSource): Background {
return new Background(this.color, value, this.repeat, this.position, this.size);
}
public withRepeat(value: string): Background {
return new Background(this.color, this.image, value, this.position, this.size);
}
public withPosition(value: string): Background {
return new Background(this.color, this.image, this.repeat, value, this.size);
}
public withSize(value: string): Background {
return new Background(this.color, this.image, this.repeat, this.position, value);
}
public getDrawParams(width: number, height: number): dts.BackgroundDrawParams {
if (!this.image) {
return null;
}
var res: dts.BackgroundDrawParams = {
repeatX: true,
repeatY: true,
posX: 0,
posY: 0,
}
// repeat
if (this.repeat) {
switch (this.repeat.toLowerCase()) {
case enums.BackgroundRepeat.noRepeat:
res.repeatX = false;
res.repeatY = false;
break;
case enums.BackgroundRepeat.repeatX:
res.repeatY = false;
break;
case enums.BackgroundRepeat.repeatY:
res.repeatX = false;
break;
}
}
var imageWidth = this.image.width;
var imageHeight = this.image.height;
// size
if (this.size) {
let values = cssValue.parse(this.size);
console.log("this.size values: " + JSON.stringify(values));
if (values.length === 2) {
let vx = values[0];
let vy = values[1];
if (vx.unit === "%" && vy.unit === "%") {
imageWidth = width * vx.value / 100;
imageHeight = height * vy.value / 100;
res.sizeX = imageWidth;
res.sizeY = imageHeight;
}
else if (vx.type === "number" && vy.type === "number" &&
((vx.unit === "px" && vy.unit === "px") || (vx.unit === "" && vy.unit === ""))) {
imageWidth = vx.value;
imageHeight = vy.value;
res.sizeX = imageWidth;
res.sizeY = imageHeight;
}
}
else if (values.length === 1 && values[0].type === "ident") {
let scale = 0;
if (values[0].string === "cover") {
scale = Math.max(width / imageWidth, height / imageHeight);
}
else if (values[0].string === "contain") {
scale = Math.min(width / imageWidth, height / imageHeight);
}
if(scale > 0){
imageWidth *= scale;
imageHeight *= scale;
res.sizeX = imageWidth;
res.sizeY = imageHeight;
}
}
}
// position
if (this.position) {
let values = cssValue.parse(this.position);
console.log("this.position values: " + JSON.stringify(values));
let spaceX = width - imageWidth;
let spaceY = height - imageHeight;
if (values.length === 2) {
let vx = values[0];
let vy = values[1];
if (vx.unit === "%" && vy.unit === "%") {
res.posX = spaceX * vx.value / 100;
res.posY = spaceY * vy.value / 100;
}
else if (vx.type === "number" && vy.type === "number" &&
((vx.unit === "px" && vy.unit === "px") || (vx.unit === "" && vy.unit === ""))) {
res.posX = vx.value;
res.posY = vy.value;
}
else if (vx.type === "ident" && vy.type === "ident") {
if (vx.string.toLowerCase() === "center") {
res.posX = spaceX / 2;
}
else if (vx.string.toLowerCase() === "right") {
res.posX = spaceX;
}
if (vy.string.toLowerCase() === "center") {
res.posY = spaceY / 2;
}
else if (vy.string.toLowerCase() === "bottom") {
res.posY = spaceY;
}
}
}
}
return res;
}
public isEmpty(): boolean {
return types.isUndefined(this.image) && types.isUndefined(this.color);
}
public static equals(value1: Background, value2: Background): boolean {
// both values are falsy
if (!value1 && !value2) {
return true;
}
// only one is falsy
if (!value1 || !value2) {
return false;
}
return value1.image === value2.image &&
value1.position === value2.position &&
value1.repeat === value2.repeat &&
value1.size === value2.size &&
colorModule.Color.equals(value1.color, value2.color);
}
}

View File

@ -0,0 +1,134 @@
import imageSource = require("image-source");
import colorModule = require("color");
import viewModule = require("ui/core/view");
import style = require("ui/styling/style");
import types = require("utils/types");
import view = require("ui/core/view");
import enums = require("ui/enums");
import utils = require("utils/utils");
import common = require("ui/styling/background-common");
import dts = require("ui/styling/background");
declare var exports;
require("utils/module-merge").merge(common, exports);
// We are using "ad" here to avoid namespace collision with the global android object
export module ad {
export class BorderGradientDrawable extends android.graphics.drawable.GradientDrawable implements dts.ad.BorderGradientDrawable {
private _density = utils.layout.getDisplayDensity();
constructor() {
super();
return global.__native(this);
}
private _borderWidth: number;
get borderWidth(): number {
return this._borderWidth;
}
set borderWidth(value: number) {
if (this._borderWidth !== value) {
this._borderWidth = value;
this.setStroke(this._borderWidth * this._density, this._borderColor);
}
}
private _cornerRadius: number;
get cornerRadius(): number {
return this._cornerRadius;
}
set cornerRadius(value: number) {
if (this._cornerRadius !== value) {
this._cornerRadius = value;
this.setCornerRadius(this._cornerRadius * this._density);
}
}
private _borderColor: number;
get borderColor(): number {
return this._borderColor;
}
set borderColor(value: number) {
if (this._borderColor !== value) {
this._borderColor = value;
this.setStroke(this._borderWidth * this._density, this._borderColor);
}
}
private _background: common.Background
get background(): common.Background {
return this._background;
}
set background(value: common.Background) {
if (this._background !== value) {
this._background = value;
this.invalidateSelf();
}
}
public draw(canvas: android.graphics.Canvas): void {
super.draw(canvas);
console.log("BorderGradientDrawable.draw()");
var bounds = this.getBounds();
var boundsWidth = bounds.width();
var boundsHeight = bounds.height();
if (this.background && !this.background.isEmpty() && boundsWidth > 0 && boundsHeight > 0) {
var bitmap = this.background.image.android;
var radius = this._cornerRadius * this._density;
var stroke = this._borderWidth * this._density;
var bounds = this.getBounds();
// TODO: check this path
var path = new android.graphics.Path();
path.addRoundRect(new android.graphics.RectF(stroke, stroke, bounds.right - stroke, bounds.bottom - stroke), radius, radius, android.graphics.Path.Direction.CW);
canvas.clipPath(path);
if (this.background.color && this.background.color.android) {
var c = this.background.color;
canvas.drawARGB(c.a, c.r, c.g, c.b);
}
if (this.background.image) {
var params = this.background.getDrawParams(boundsWidth, boundsHeight);
var matrix = new android.graphics.Matrix();
if (params.sizeX > 0 && params.sizeY > 0) {
var scaleX = params.sizeX / bitmap.getWidth();
var scaleY = params.sizeY / bitmap.getHeight();
matrix.setScale(scaleX, scaleY, 0, 0);
}
else {
params.sizeX = bitmap.getWidth();
params.sizeY = bitmap.getHeight();
}
matrix.postTranslate(params.posX, params.posY);
if (!params.repeatX && !params.repeatY) {
canvas.drawBitmap(bitmap, matrix, undefined);
}
else {
var shader = new android.graphics.BitmapShader(bitmap, android.graphics.Shader.TileMode.REPEAT, android.graphics.Shader.TileMode.REPEAT);
shader.setLocalMatrix(matrix);
var paint = new android.graphics.Paint();
paint.setShader(shader);
var w = params.repeatX ? bounds.width() : params.sizeX;
var h = params.repeatY ? bounds.height() : params.sizeY;
params.posX = params.repeatX ? 0 : params.posX;
params.posY = params.repeatY ? 0 : params.posY;
canvas.drawRect(params.posX, params.posY, params.posX + w, params.posY + h, paint);
}
}
}
}
}
}

64
ui/styling/background.d.ts vendored Normal file
View File

@ -0,0 +1,64 @@
declare module "ui/styling/background" {
import imageSource = require("image-source");
import colorModule = require("color");
import viewModule = require("ui/core/view");
import style = require("ui/styling/style");
import types = require("utils/types");
import view = require("ui/core/view");
import enums = require("ui/enums");
import utils = require("utils/utils");
export interface BackgroundDrawParams {
repeatX: boolean;
repeatY: boolean;
posX: number;
posY: number;
sizeX?: number;
sizeY?: number;
}
export class Background {
static default: Background;
color: colorModule.Color;
image: imageSource.ImageSource;
repeat: string;
position: string;
size: string;
constructor(
color: colorModule.Color,
image: imageSource.ImageSource,
repeat: string,
position: string,
size: string);
public withColor(value: colorModule.Color): Background;
public withImage(value: imageSource.ImageSource): Background;
public withRepeat(value: string): Background;
public withPosition(value: string): Background;
public withSize(value: string): Background;;
public getDrawParams(width: number, height: number): BackgroundDrawParams;
public isEmpty(): boolean;
public static equals(value1: Background, value2: Background): boolean;
}
export module ios {
export function createBackgroundUIColor(view: viewModule.View): UIColor;
}
// We are using "ad" here to avoid namespace collision with the global android object
export module ad {
export class BorderGradientDrawable extends android.graphics.drawable.GradientDrawable {
borderWidth: number;
cornerRadius: number;
borderColor: number;
background: Background;
}
}
}

View File

@ -0,0 +1,74 @@
import imageSource = require("image-source");
import colorModule = require("color");
import viewModule = require("ui/core/view");
import style = require("ui/styling/style");
import types = require("utils/types");
import view = require("ui/core/view");
import enums = require("ui/enums");
import utils = require("utils/utils");
import common = require("ui/styling/background-common");
import dts = require("ui/styling/background");
declare var exports;
require("utils/module-merge").merge(common, exports);
export module ios {
export function createBackgroundUIColor(view: viewModule.View): UIColor {
var background = <common.Background> view.style._getValue(style.backgroundInternalProperty);
var frame = (<UIView>view._nativeView).frame;
var result: UIColor;
if (background && !background.isEmpty() && frame.size.width > 0 && frame.size.height) {
console.log("Frame: " + NSStringFromCGRect(frame));
if (!background.image) {
result = background.color.ios;
}
else {
var img = <UIImage>background.image.ios;
console.log("ImageSize: " + NSStringFromCGSize(img.size));
var params = background.getDrawParams(frame.size.width, frame.size.height);
if (params.sizeX > 0 && params.sizeY > 0) {
var resizeRect = CGRectMake(0, 0, params.sizeX, params.sizeY);
UIGraphicsBeginImageContext(resizeRect.size);
img.drawInRect(resizeRect);
img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
UIGraphicsBeginImageContextWithOptions(frame.size, false, 1.0);
var context = UIGraphicsGetCurrentContext();
if (background.color && background.color.ios) {
CGContextSetFillColorWithColor(context, background.color.ios.CGColor);
CGContextFillRect(context, frame);
}
if (!params.repeatX && !params.repeatY) {
img.drawAtPoint(CGPointMake(params.posX, params.posY));
}
else {
var w = params.repeatX ? frame.size.width : img.size.width;
var h = params.repeatY ? frame.size.height : img.size.height;
CGContextSetPatternPhase(context, CGSizeMake(params.posX, params.posY));
console.log("context" + context);
params.posX = params.repeatX ? 0 : params.posX;
params.posY = params.repeatY ? 0 : params.posY;
var patternRect = CGRectMake(params.posX, params.posY, w, h);
console.log("patternRect: " + NSStringFromCGRect(patternRect));
img.drawAsPatternInRect(patternRect);
}
var bkgImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
console.log("bkgImage.size: " + NSStringFromCGSize(bkgImage.size));
result = UIColor.alloc().initWithPatternImage(bkgImage);
}
return result;
}
}
}

View File

@ -12,6 +12,7 @@ import enums = require("ui/enums");
import imageSource = require("image-source");
import utils = require("utils/utils");
import font = require("ui/styling/font");
import background = require("ui/styling/background");
// key is the property id and value is Dictionary<string, StylePropertyChangedHandler>;
var _registeredHandlers = Array<Object>();
@ -48,6 +49,27 @@ export class Style extends observable.DependencyObservable implements styling.St
this._setValue(backgroundImageProperty, value, observable.ValueSource.Local);
}
get backgroundRepeat(): string {
return this._getValue(backgroundRepeatProperty);
}
set backgroundRepeat(value: string) {
this._setValue(backgroundRepeatProperty, value, observable.ValueSource.Local);
}
get backgroundSize(): string {
return this._getValue(backgroundSizeProperty);
}
set backgroundSize(value: string) {
this._setValue(backgroundSizeProperty, value, observable.ValueSource.Local);
}
get backgroundPosition(): string {
return this._getValue(backgroundPositionProperty);
}
set backgroundPosition(value: string) {
this._setValue(backgroundPositionProperty, value, observable.ValueSource.Local);
}
get borderColor(): color.Color {
return this._getValue(borderColorProperty);
}
@ -241,7 +263,7 @@ export class Style extends observable.DependencyObservable implements styling.St
super();
this._view = parentView;
}
public _beginUpdate() {
this._inUpdate = true;
}
@ -317,7 +339,7 @@ export class Style extends observable.DependencyObservable implements styling.St
}
else {
trace.write("Found handler for property: " + property.name + ", view:" + this._view, trace.categories.Style);
var shouldReset = false;
if (property.metadata.equalityComparer) {
shouldReset = property.metadata.equalityComparer(newValue, property.metadata.defaultValue);
@ -426,39 +448,18 @@ export var colorProperty = new styleProperty.Property("color", "color",
export var backgroundImageProperty = new styleProperty.Property("backgroundImage", "background-image",
new observable.PropertyMetadata(undefined, observable.PropertyMetadataSettings.None, onBackgroundImagePropertyChanged));
function onBackgroundImagePropertyChanged(data: observable.PropertyChangeData) {
var view: view.View = (<any>data.object)._view;
var style = <Style>data.object;
var url: string = data.newValue;
export var backgroundColorProperty = new styleProperty.Property("backgroundColor", "background-color",
new observable.PropertyMetadata(undefined, observable.PropertyMetadataSettings.None, onBackgroundColorPropertyChanged, undefined, color.Color.equals),
converters.colorConverter);
style._setValue(backgroundImageSourceProperty, undefined, observable.ValueSource.Local);
export var backgroundRepeatProperty = new styleProperty.Property("backgroundRepeat", "background-repeat",
new observable.PropertyMetadata(undefined, observable.PropertyMetadataSettings.None, onBackgroundRepeatPropertyChanged));
if (types.isString(data.newValue)) {
var pattern: RegExp = /url\(('|")(.*?)\1\)/;
var match = url.match(pattern);
if (match && match[2]) {
url = match[2];
}
export var backgroundSizeProperty = new styleProperty.Property("backgroundSize", "background-size",
new observable.PropertyMetadata(undefined, observable.PropertyMetadataSettings.None, onBackgroundSizePropertyChanged));
if (utils.isDataURI(url)) {
var base64Data = url.split(",")[1];
if (types.isDefined(base64Data)) {
style._setValue(backgroundImageSourceProperty, imageSource.fromBase64(base64Data), observable.ValueSource.Local);
}
} else if (utils.isFileOrResourcePath(url)) {
style._setValue(backgroundImageSourceProperty, imageSource.fromFileOrResource(url), observable.ValueSource.Local);
} else if (url.indexOf("http") !== -1) {
if (view) {
view["_url"] = url;
}
imageSource.fromUrl(url).then(r=> {
if (view && view["_url"] === url) {
style._setValue(backgroundImageSourceProperty, r, observable.ValueSource.Local);
}
});
}
}
}
export var backgroundPositionProperty = new styleProperty.Property("backgroundPosition", "background-position",
new observable.PropertyMetadata(undefined, observable.PropertyMetadataSettings.None, onBackgroundPositionPropertyChanged));
export var borderColorProperty = new styleProperty.Property("borderColor", "border-color",
new observable.PropertyMetadata(undefined, observable.PropertyMetadataSettings.None, undefined, undefined, color.Color.equals),
@ -470,18 +471,77 @@ export var borderWidthProperty = new styleProperty.Property("borderWidth", "bord
export var borderRadiusProperty = new styleProperty.Property("borderRadius", "border-radius",
new observable.PropertyMetadata(0, observable.PropertyMetadataSettings.AffectsLayout, null, isPaddingValid), converters.numberConverter);
export var backgroundImageSourceProperty = new styleProperty.Property("backgroundImageSource", "background-image-source",
new observable.PropertyMetadata(undefined, observable.PropertyMetadataSettings.None, undefined, undefined, undefined));
export var backgroundInternalProperty = new styleProperty.Property("_backgroundInternal", "_backgroundInternal",
new observable.PropertyMetadata(background.Background.default, observable.PropertyMetadataSettings.None, undefined, undefined, background.Background.equals));
export var backgroundColorProperty = new styleProperty.Property("backgroundColor", "background-color",
new observable.PropertyMetadata(undefined, observable.PropertyMetadataSettings.None, undefined, undefined, color.Color.equals),
converters.colorConverter);
function onBackgroundImagePropertyChanged(data: observable.PropertyChangeData) {
var style = <Style>data.object;
var url: string = data.newValue;
var currentBackground = <background.Background>style._getValue(backgroundInternalProperty);
if (types.isString(data.newValue)) {
var pattern: RegExp = /url\(('|")(.*?)\1\)/;
var match = url.match(pattern);
if (match && match[2]) {
url = match[2];
}
if (utils.isDataURI(url)) {
var base64Data = url.split(",")[1];
if (types.isDefined(base64Data)) {
style._setValue(backgroundInternalProperty, currentBackground.withImage(imageSource.fromBase64(base64Data)));
}
} else if (utils.isFileOrResourcePath(url)) {
style._setValue(backgroundInternalProperty, currentBackground.withImage(imageSource.fromFileOrResource(url)));
} else if (url.indexOf("http") !== -1) {
style["_url"] = url;
style._setValue(backgroundInternalProperty, currentBackground.withImage(undefined));
imageSource.fromUrl(url).then((r) => {
if (style && style["_url"] === url) {
style._setValue(backgroundInternalProperty, currentBackground.withImage(r));
}
});
}
}
}
function onBackgroundColorPropertyChanged(data: observable.PropertyChangeData) {
var style = <Style>data.object;
var currentBackground = <background.Background>style._getValue(backgroundInternalProperty);
if (!color.Color.equals(currentBackground.color, data.newValue)) {
style._setValue(backgroundInternalProperty, currentBackground.withColor(data.newValue));
}
}
function onBackgroundSizePropertyChanged(data: observable.PropertyChangeData) {
var style = <Style>data.object;
var currentBackground = <background.Background>style._getValue(backgroundInternalProperty);
if (data.newValue !== currentBackground.size) {
style._setValue(backgroundInternalProperty, currentBackground.withSize(data.newValue));
}
}
function onBackgroundRepeatPropertyChanged(data: observable.PropertyChangeData) {
var style = <Style>data.object;
var currentBackground = <background.Background>style._getValue(backgroundInternalProperty);
if (data.newValue !== currentBackground.repeat) {
style._setValue(backgroundInternalProperty, currentBackground.withRepeat(data.newValue));
}
}
function onBackgroundPositionPropertyChanged(data: observable.PropertyChangeData) {
var style = <Style>data.object;
var currentBackground = <background.Background>style._getValue(backgroundInternalProperty);
if (data.newValue !== currentBackground.position) {
style._setValue(backgroundInternalProperty, currentBackground.withPosition(data.newValue));
}
}
export var fontProperty = new styleProperty.Property("font", "font",
new observable.PropertyMetadata(undefined, observable.PropertyMetadataSettings.None, onFontChanged));
export var fontSizeProperty = new styleProperty.Property("fontSize", "font-size",
new observable.PropertyMetadata(undefined, observable.PropertyMetadataSettings.Inheritable, onFontSizeChanged),converters.fontSizeConverter);
new observable.PropertyMetadata(undefined, observable.PropertyMetadataSettings.Inheritable, onFontSizeChanged), converters.fontSizeConverter);
export var fontFamilyProperty = new styleProperty.Property("fontFamily", "font-family",
new observable.PropertyMetadata(undefined, observable.PropertyMetadataSettings.Inheritable, onFontFamilyChanged));
@ -543,7 +603,7 @@ function onFontChanged(data: observable.PropertyChangeData) {
var style = <Style>data.object;
var newFont = font.Font.parse(data.newValue);
var valueSource = style._getValueSource(fontProperty);
var valueSource = style._getValueSource(fontProperty);
style._setValue(fontFamilyProperty, newFont.fontFamily, valueSource);
style._setValue(fontStyleProperty, newFont.fontStyle, valueSource);
style._setValue(fontWeightProperty, newFont.fontWeight, valueSource);

View File

@ -1,5 +1,4 @@
import types = require("utils/types");
import trace = require("trace");
import view = require("ui/core/view");
import border = require("ui/border");
import constants = require("utils/android_constants");
@ -9,152 +8,26 @@ import stylersCommon = require("ui/styling/stylers-common");
import enums = require("ui/enums");
import utils = require("utils/utils");
import styleModule = require("ui/styling/style");
import imageSource = require("image-source");
import font = require("ui/styling/font");
import background = require("ui/styling/background");
// merge the exports of the common file with the exports of this file
declare var exports;
require("utils/module-merge").merge(stylersCommon, exports);
class BorderGradientDrawable extends android.graphics.drawable.GradientDrawable {
private _density = utils.layout.getDisplayDensity();
constructor() {
super();
return global.__native(this);
}
private _borderWidth: number;
get borderWidth(): number {
return this._borderWidth;
}
set borderWidth(value: number) {
if (this._borderWidth !== value) {
this._borderWidth = value;
this.setStroke(this._borderWidth * this._density, this._borderColor);
}
}
private _cornerRadius: number;
get cornerRadius(): number {
return this._cornerRadius;
}
set cornerRadius(value: number) {
if (this._cornerRadius !== value) {
this._cornerRadius = value;
this.setCornerRadius(this._cornerRadius * this._density);
}
}
private _borderColor: number;
get borderColor(): number {
return this._borderColor;
}
set borderColor(value: number) {
if (this._borderColor !== value) {
this._borderColor = value;
this.setStroke(this._borderWidth * this._density, this._borderColor);
}
}
private _backgroundColor: number;
get backgroundColor(): number {
return this._backgroundColor;
}
set backgroundColor(value: number) {
if (this._backgroundColor !== value) {
this._backgroundColor = value;
this.setColor(this._backgroundColor);
}
}
private _bitmap: android.graphics.Bitmap
get bitmap(): android.graphics.Bitmap {
return this._bitmap;
}
set bitmap(value: android.graphics.Bitmap) {
if (this._bitmap !== value) {
this._bitmap = value;
this.invalidateSelf();
}
}
public draw(canvas: android.graphics.Canvas): void {
super.draw(canvas);
console.log("BorderGradientDrawable.draw()");
if (this.bitmap) {
var radius = this._cornerRadius * this._density;
var stroke = this._borderWidth * this._density;
var bounds = this.getBounds();
var path = new android.graphics.Path();
path.addRoundRect(new android.graphics.RectF(stroke, stroke, bounds.right - stroke, bounds.bottom - stroke), radius, radius, android.graphics.Path.Direction.CW);
canvas.clipPath(path);
if (this.bitmap) {
var repeatX = true;
var repeatY = true;
var posX = 15;
var posY = 35;
var sizeX = 100;
var sizeY = 150;
var matrix = new android.graphics.Matrix();
if (sizeX > 0 && sizeY > 0) {
var scaleX = sizeX / this.bitmap.getWidth();
var scaleY = sizeY / this.bitmap.getHeight();
matrix.setScale(scaleX, scaleY, 0, 0);
}
else {
sizeX = this.bitmap.getWidth();
sizeY = this.bitmap.getHeight();
}
matrix.postTranslate(posX, posY);
if (!repeatX && !repeatY) {
canvas.drawBitmap(this.bitmap, matrix, undefined);
}
else {
var shader = new android.graphics.BitmapShader(this.bitmap, android.graphics.Shader.TileMode.REPEAT, android.graphics.Shader.TileMode.REPEAT);
shader.setLocalMatrix(matrix);
var paint = new android.graphics.Paint();
paint.setShader(shader);
var w = repeatX ? bounds.width() : sizeX;
var h = repeatY ? bounds.height() : sizeY;
posX = repeatX ? 0 : posX;
posY = repeatY ? 0 : posY;
canvas.drawRect(posX, posY, posX + w, posY + h, paint);
}
}
}
}
}
function onBorderPropertyChanged(v: view.View) {
if (!v._nativeView) {
return;
}
var value = <imageSource.ImageSource>v.style._getValue(styleModule.backgroundImageSourceProperty);
var backgroundValue = <background.Background>v.style._getValue(styleModule.backgroundInternalProperty);
if (v.borderWidth !== 0 || v.borderRadius !== 0 || !types.isNullOrUndefined(v.backgroundColor) || !types.isNullOrUndefined(value)) {
if (v.borderWidth !== 0 || v.borderRadius !== 0 || !backgroundValue.isEmpty()) {
var nativeView = <android.view.View>v._nativeView;
var bkg = <BorderGradientDrawable>nativeView.getBackground();
if (!(bkg instanceof BorderGradientDrawable)) {
bkg = new BorderGradientDrawable();
var bkg = <background.ad.BorderGradientDrawable>nativeView.getBackground();
if (!(bkg instanceof background.ad.BorderGradientDrawable)) {
bkg = new background.ad.BorderGradientDrawable();
nativeView.setBackground(bkg);
}
@ -165,47 +38,23 @@ function onBorderPropertyChanged(v: view.View) {
bkg.borderWidth = v.borderWidth;
bkg.cornerRadius = v.borderRadius;
bkg.borderColor = v.borderColor ? v.borderColor.android : android.graphics.Color.TRANSPARENT;
bkg.backgroundColor = v.backgroundColor ? v.backgroundColor.android : android.graphics.Color.TRANSPARENT;
bkg.bitmap = value ? value.android : undefined;
bkg.background = backgroundValue;
}
}
export class DefaultStyler implements definition.stylers.Styler {
//Background methods
private static setBackgroundProperty(view: view.View, newValue: any) {
onBorderPropertyChanged(view);
}
private static resetBackgroundProperty(view: view.View, nativeValue: any) {
if (types.isDefined(nativeValue)) {
(<android.view.View>view.android).setBackground(nativeValue)
}
}
private static getNativeBackgroundValue(view: view.View): any {
var drawable = view.android.getBackground();
if (drawable instanceof android.graphics.drawable.StateListDrawable) {
// StateListDrawables should not be cached as they should be created per instance of view as they contain the current state within.
trace.write("Native value of view: " + view + " is StateListDrawable. It will not be cached.", trace.categories.Style);
return undefined;
}
return drawable;
}
//Background image methods
private static setBackgroundImageSourceProperty(view: view.View, newValue: any) {
private static setBackgroundInternalProperty(view: view.View, newValue: any) {
onBorderPropertyChanged(view);
}
private static resetBackgroundImageSourceProperty(view: view.View, nativeValue: any) {
private static resetBackgroundInternalProperty(view: view.View, nativeValue: any) {
if (types.isDefined(nativeValue)) {
(<android.view.View>view.android).setBackgroundDrawable(nativeValue)
}
}
private static getNativeBackgroundImageSourceValue(view: view.View): any {
private static getNativeBackgroundInternalProperty(view: view.View): any {
return view.android.getBackground();
}
@ -215,7 +64,7 @@ export class DefaultStyler implements definition.stylers.Styler {
}
private static resetBorderWidthProperty(view: view.View, nativeValue: any) {
view.borderWidth = 0;
//TODO
}
//Border color methods
@ -224,7 +73,7 @@ export class DefaultStyler implements definition.stylers.Styler {
}
private static resetBorderColorProperty(view: view.View, nativeValue: any) {
view.borderColor = undefined;
//TODO
}
//Corner radius methods
@ -233,7 +82,7 @@ export class DefaultStyler implements definition.stylers.Styler {
}
private static resetBorderRadiusProperty(view: view.View, nativeValue: any) {
view.borderRadius = 0;
//TODO
}
//Visibility methods
@ -274,15 +123,10 @@ export class DefaultStyler implements definition.stylers.Styler {
}
public static registerHandlers() {
style.registerHandler(style.backgroundColorProperty, new stylersCommon.StylePropertyChangedHandler(
DefaultStyler.setBackgroundProperty,
DefaultStyler.resetBackgroundProperty,
DefaultStyler.getNativeBackgroundValue));
style.registerHandler(style.backgroundImageSourceProperty, new stylersCommon.StylePropertyChangedHandler(
DefaultStyler.setBackgroundImageSourceProperty,
DefaultStyler.resetBackgroundImageSourceProperty,
DefaultStyler.getNativeBackgroundImageSourceValue));
style.registerHandler(style.backgroundInternalProperty, new stylersCommon.StylePropertyChangedHandler(
DefaultStyler.setBackgroundInternalProperty,
DefaultStyler.resetBackgroundInternalProperty,
DefaultStyler.getNativeBackgroundInternalProperty));
style.registerHandler(style.visibilityProperty, new stylersCommon.StylePropertyChangedHandler(
DefaultStyler.setVisibilityProperty,

View File

@ -4,6 +4,7 @@ import definition = require("ui/styling");
import stylersCommon = require("ui/styling/stylers-common");
import enums = require("ui/enums");
import font = require("ui/styling/font");
import background = require("ui/styling/background");
// merge the exports of the common file with the exports of this file
declare var exports;
@ -17,44 +18,21 @@ interface TextUIView {
export class DefaultStyler implements definition.stylers.Styler {
//Background methods
private static setBackgroundProperty(view: view.View, newValue: any) {
private static setBackgroundInternalProperty(view: view.View, newValue: any) {
var nativeView: UIView = <UIView>view._nativeView;
if (nativeView) {
nativeView.backgroundColor = newValue;
nativeView.backgroundColor = background.ios.createBackgroundUIColor(view);
}
}
private static resetBackgroundProperty(view: view.View, nativeValue: any) {
private static resetBackgroundInternalProperty(view: view.View, nativeValue: any) {
var nativeView: UIView = <UIView>view._nativeView;
if (nativeView) {
nativeView.backgroundColor = nativeValue;
}
}
private static getNativeBackgroundValue(view: view.View): any {
var nativeView: UIView = <UIView>view._nativeView;
if (nativeView) {
return nativeView.backgroundColor;
}
return undefined;
}
//Background image methods
private static setBackgroundImageSourceProperty(view: view.View, newValue: any) {
var nativeView: UIView = <UIView>view._nativeView;
if (nativeView) {
nativeView.backgroundColor = UIColor.alloc().initWithPatternImage(newValue);
}
}
private static resetBackgroundImageSourceProperty(view: view.View, nativeValue: any) {
var nativeView: UIView = <UIView>view._nativeView;
if (nativeView) {
nativeView.backgroundColor = nativeValue;
}
}
private static getNativeBackgroundImageSourceValue(view: view.View): any {
private static getNativeBackgroundInternalValue(view: view.View): any {
var nativeView: UIView = <UIView>view._nativeView;
if (nativeView) {
return nativeView.backgroundColor;
@ -132,15 +110,10 @@ export class DefaultStyler implements definition.stylers.Styler {
}
public static registerHandlers() {
style.registerHandler(style.backgroundColorProperty, new stylersCommon.StylePropertyChangedHandler(
DefaultStyler.setBackgroundProperty,
DefaultStyler.resetBackgroundProperty,
DefaultStyler.getNativeBackgroundValue));
//style.registerHandler(style.backgroundImageSourceProperty, new stylersCommon.StylePropertyChangedHandler(
// DefaultStyler.setBackgroundImageSourceProperty,
// DefaultStyler.resetBackgroundImageSourceProperty,
// DefaultStyler.getNativeBackgroundImageSourceValue));
style.registerHandler(style.backgroundInternalProperty, new stylersCommon.StylePropertyChangedHandler(
DefaultStyler.setBackgroundInternalProperty,
DefaultStyler.resetBackgroundInternalProperty,
DefaultStyler.getNativeBackgroundInternalValue));
style.registerHandler(style.visibilityProperty, new stylersCommon.StylePropertyChangedHandler(
DefaultStyler.setVisibilityProperty,

View File

@ -47,6 +47,26 @@
* Gets or sets the background-color style property.
*/
backgroundColor: color.Color;
/**
* Gets or sets the background-image style property.
*/
backgroundImage: string;
/**
* Gets or sets the background-size style property.
*/
backgroundSize: string;
/**
* Gets or sets the background-position style property.
*/
backgroundPosition: string;
/**
* Gets or sets the background-repeat style property.
*/
backgroundRepeat: string;
/**
* Gets or sets font-size style property.