我需要在背景图像上添加渐变。我已经将图片设置为页面的背景,但我无法弄清楚如何在Android中添加Gradient。我在iOS上做了以下几点:
public class GradientContentPageRenderer : PageRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (e.OldElement == null) // perform initial setup
{
var page = e.NewElement as GradientContentPage;
var gradientLayer = new CAGradientLayer();
gradientLayer.Frame = View.Bounds;
gradientLayer.Locations = new NSNumber[] { 0.2,0.8} ;
gradientLayer.Colors = new CGColor[] { page.StartColor.ToCGColor(), page.EndColor.ToCGColor() };
View.Layer.InsertSublayer(gradientLayer, 0);
}
}
}
我知道如何使用Drawable与Android创建渐变但我无法弄清楚如何将其添加为图层。如果可能,我想通过使用自定义渲染器在渲染时注入新的相对布局,但我无法弄清楚如何做到这一点。请记住,我需要保留现有的背景图像,我只想在顶部放置一个渐变。
有没有办法动态插入额外的布局和渲染时间?或者我应该采取不同的方法吗?
答案 0 :(得分:0)
protected override void DispatchDraw(global::Android.Graphics.Canvas canvas)
{
base.DispatchDraw(canvas);
var gradient = new Android.Graphics.LinearGradient(0, 0, 0, Height,
Color.FromRgba(255, 255, 255, 100).ToAndroid(),
Color.FromRgba(0, 0, 0, 100).ToAndroid(),
Android.Graphics.Shader.TileMode.Mirror);
var paint = new Android.Graphics.Paint() {
Dither = true,
};
paint.SetShader(gradient);
canvas.DrawPaint(paint);
}
要将所有控件放在渐变顶部,只需将base.DispatchDraw(canvas);
放在底部:
protected override void DispatchDraw(global::Android.Graphics.Canvas canvas)
{
var gradient = new Android.Graphics.LinearGradient(0, 0, 0, Height,
Color.FromRgba(255, 255, 255, 100).ToAndroid(),
Color.FromRgba(0, 0, 0, 100).ToAndroid(),
Android.Graphics.Shader.TileMode.Mirror);
var paint = new Android.Graphics.Paint() {
Dither = true,
};
paint.SetShader(gradient);
canvas.DrawPaint(paint);
base.DispatchDraw(canvas);
}