IMG上的黑色渐变层不使用线性渐变?

时间:2017-03-17 12:34:32

标签: html css css3

我有一个img标签,我想在它上面添加另一个渐变div图层(渐变div将有文字)。

这样的事情:

enter image description here

我已经知道我can do this with linear-gradient但我不希望这样,因为并非所有移动版本都支持此功能。

另外 - 我已经看到它可以实现via box-shadow with inset

enter image description here

但它不一样。我想要顶部和底部渐变 - 边缘没有任何差异。 (就像在我的第一张照片中^)

This is what i've tried : JSBIN

enter image description here

但同样,我不希望边缘变暗。我只希望红色矩形中的条带从左到右。并且 - 对称 - 在底部(相同的渐变应该在底部)。

问题

如何在不使用linear-gradient的情况下修复我的代码以在顶部和底部实现直线相等的渐变?

NB

  

我需要在该渐变div上添加文本(文本来自DB)。所以它不能是伪:: before / :: after元素div。

3 个答案:

答案 0 :(得分:2)

正如我在评论中建议的那样,如果您可以使用pseudo元素作为::after容器 DOM ::beforeimg来实现此目的元件。

您可以定义pseudo元素,然后使用box-shadow来复制该渐变效果。

我在 DOM 结构中进行了一些更改:

代码段:



.img-container {
  position: relative;
}

.img-container img {
  max-width: 100%;
}

.img-container::after,
.img-container::before {
  content: "";
  display: inline-block;
  position: absolute;
  left: 0;
  right: 0;
  width: 100%;
  height: 50px;
}

.img-container::before {
  top: 0;
  -webkit-box-shadow: 0px 25px 16px -10px rgba(0, 0, 0, 0.5) inset;
  box-shadow: 0px 25px 16px -10px rgba(0, 0, 0, 0.5) inset;
}

.img-container::after {
  bottom: 0;
  -webkit-box-shadow: 0px -25px 16px -10px rgba(0, 0, 0, 0.5) inset;
  box-shadow: 0px -25px 16px -10px rgba(0, 0, 0, 0.5) inset;
}

<div class="img-container">
  <img src='http://blog.caranddriver.com/wp-content/uploads/2015/11/BMW-2-series.jpg' height="400px" />
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

通过使用多个阴影,您可以定位所需的边。

这里完成了将模糊的展开半径(第4个参数)设置为负值,防止它沿侧面扩散,并使用水平和阴影的垂直偏移量,在这种情况下,仅针对顶部和底部。

&#13;
&#13;
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Collections.Generic;
using System.IO;
using Android.Graphics;
using Microsoft.WindowsAzure.MobileServices;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.MobileServices.Sync;
using Microsoft.WindowsAzure.MobileServices.SQLiteStore;
using Android.Util;

namespace CarryARideAnyWere
 {
    [Activity(Label = "SignUpActivity", Theme = "@style/MyAppTheme")]
public class SignUpActivity : Activity
{
    AutoCompleteTextView Cities;
    EditText userName;
    EditText passward;
    EditText retypePassward;
    EditText phone;
    EditText work;
    Button register;
    ImageView profilePic;
    Bitmap bit;
    byte[] b;
    private MobileServiceClient client;
    private IMobileServiceSyncTable<ClientData> clientData;
    const string LocalDBFileName = "ClientDataFile";
    const string ApplicationURL =        "http://carryarideanywhere.azurewebsites.net/";
    protected override async void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Create your application here
        SetContentView(Resource.Layout.SignUp);
        //perform plateform related initialization
        CurrentPlatform.Init();
        //to get City of user
        Cities = FindViewById<AutoCompleteTextView>(Resource.Id.City);
        //geting Layout widgets
        userName = FindViewById<EditText>(Resource.Id.userName);
        passward = FindViewById<EditText>(Resource.Id.passward);
        retypePassward = FindViewById<EditText>(Resource.Id.reenterpass);
        phone = FindViewById<EditText>(Resource.Id.PhoneNumber);
        work = FindViewById<EditText>(Resource.Id.work);
        profilePic = FindViewById<ImageView>(Resource.Id.profilepic);
        register = FindViewById<Button>(Resource.Id.Register);
        //Geting Array of Cities
        String[] citiesofPak =     Resources.GetStringArray(Resource.Array.cities);
        Cities.Adapter = new ArrayAdapter<string>(this,         Resource.Layout.CitiesView, citiesofPak);

        //Creating client object 
        client = new MobileServiceClient(ApplicationURL);
        //Initializing LocalStore 
        await InitLocalStoreAsync();
        clientData = client.GetSyncTable<ClientData>();
        //Defining Click Event of Register button

        register.Click += OnRegisterClick;
        //registering click event of image view
        profilePic.Click -= OnProfilePicClick;
        profilePic.Click += OnProfilePicClick;
       b = new byte[] { 12, 12, 12, 12 };



    }
    private void OnRegisterClick(object sender, EventArgs e)
    {

        if (userName.Text == string.Empty | passward.Text == string.Empty |          retypePassward.Text == string.Empty | phone.Text == string.Empty |     Cities.Text == string.Empty | work.Text == string.Empty)
        {
            CreateDialog.CreateAndShowDialog("Please fill all the Boxes",   "Error", this);
            return;
        }
        if (passward.Text != retypePassward.Text)
        {
            CreateDialog.CreateAndShowDialog("passward Does not match", "Error", this);
            return;
        }
        AddData();

        Intent intent = new Intent(this, typeof(LogInActivity));
        intent.PutExtra(Constants.Start, true);
      //  StartActivity(intent);
     //   this.Finish();


    }
    private async Task InitLocalStoreAsync()
    {
        var store = new MobileServiceSQLiteStore(LocalDBFileName);
        store.DefineTable<ClientData>();
        await client.SyncContext.InitializeAsync(store);
    }
    private async Task PushData()
    {
        try
        {


            await client.SyncContext.PushAsync();
            IMobileServiceTableQuery<ClientData> query = clientData
                                                     .Where(u => u.phone == phone.Text);
            await clientData.PullAsync(null, query);
        }
        catch (Java.Net.MalformedURLException)
        {
            CreateDialog.CreateAndShowDialog(new Exception("There was error creating MobileService verify URL"), "Error", this);
        }
        catch (Exception e)
        {
            CreateDialog.CreateAndShowDialog(e, "Error", this);
        }
    }
    public async void AddData()
    {
        if (client == null)
        {
            return;
        }
        var Data = new ClientData { userName = userName.Text, passward =     passward.Text, phone = phone.Text, city = Cities.Text, work =     work.Text,profile=convert(bit)};
        try
        {
            CreateDialog.CreateAndShowDialog(convert(bit).Length.ToString(), "bytearrylength", this);

            await clientData.InsertAsync(Data);
            await PushData();
        }
        catch (Exception e)
        {
            CreateDialog.CreateAndShowDialog(e, "Error in datauploading", this);
        }

    }
    private void OnProfilePicClick(object sender, EventArgs e)
    {
        Intent intent = new Intent();
        intent.SetType("image/*");
        intent.SetAction(Intent.ActionGetContent);
       StartActivityForResult(Intent.CreateChooser(intent, "Select a pic"), 0);
    }
    protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
    {
        base.OnActivityResult(requestCode, resultCode, data);
        if (resultCode == Result.Ok)
        {
               bit = calculateRequiredimentions(data.Data, 150, 150);
            Stream stream = ContentResolver.OpenInputStream(data.Data);
            bit = BitmapFactory.DecodeStream(stream);
            profilePic.SetImageBitmap(bit);

        }
    }
    private string convert(Bitmap bitmap)
    {
        byte[] bitmapData;
        string ImageEncoding;
        using (var stream = new MemoryStream())
        {
            bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);



            bitmapData = stream.ToArray();
            ImageEncoding=Base64.EncodeToString(bitmapData,Base64Flags.Default);
            CreateDialog.CreateAndShowDialog(bitmapData.Length.ToString(), "bytearrylength", this);
        }
        return ImageEncoding;
    }
    private Bitmap calculateRequiredimentions(Android.Net.Uri data,int requestedHeight,int requestedWidth)
    {
        Stream stream = ContentResolver.OpenInputStream(data);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.InJustDecodeBounds = true;
        BitmapFactory.DecodeStream(stream);
        options.InSampleSize = calcualteintvalue(options, requestedHeight, requestedWidth);
        stream = ContentResolver.OpenInputStream(data);
        options.InJustDecodeBounds = false;
        Bitmap map = BitmapFactory.DecodeStream(stream,null,options);
        return map;
    }
    private int calcualteintvalue(BitmapFactory.Options options,int requestedHeight,int requestedWidth)
    {
        int height = options.OutHeight;
        int width = options.OutWidth;
        int returendValue = 1;
        if (height > requestedHeight || width > requestedWidth)
        {
            int halfheight = height / 2;
            int halfwidth = width / 2;


            while ((halfheight / returendValue) > requestedHeight && (halfwidth / returendValue) > requestedWidth)
            {
                returendValue *= 2;
            }
        }
        return returendValue;
    }

}
}
&#13;
.innerDiv
{
  position:absolute;
  top:0;
  right:0;
  bottom:0;
  left:0;
  background :transparent;
  opacity:1;
  border:solid 1px red;
  padding:5px;
  z-index:92299; 
  box-shadow:
    inset 0 50px 50px -40px rgba(0,0,0,1),
    inset 0 -50px 50px -40px rgba(0,0,0,1);
}
&#13;
&#13;
&#13;

基于之前的评论,这里是一个伪元素版本,产生完全相同的结果,并使用<div style='position:relative;border:solid 1px lightgray;height:400px'> <div class='innerDiv'> Some text </div> <img src='http://blog.caranddriver.com/wp-content/uploads/2015/11/BMW-2-series.jpg' height="400px" /> </div>避免了CSS中编译时数据的问题。

我还添加了一个脚本来显示文本也可以动态添加。

&#13;
&#13;
CSS attr()
&#13;
window.addEventListener('load', function() {
  var div = document.querySelector('div');
  var text = div.getAttribute('data-text');
  div.setAttribute('data-text', text + ', and this were added dynamically using script');
})
&#13;
div
{
  position:relative;
}
div::after
{
  content: attr(data-text);
  position:absolute;
  top:0;
  right:0;
  bottom:0;
  left:0;
  background :transparent;
  opacity:1;
  border:solid 1px red;
  padding:5px;
  z-index:92299; 
  box-shadow:
    inset 0 50px 50px -40px rgba(0,0,0,1),
    inset 0 -50px 50px -40px rgba(0,0,0,1);
}
&#13;
&#13;
&#13;

答案 2 :(得分:1)

(使用@vivekkupadhyay的答案为例)你可以制作一个叠加div并给它插入阴影。然后,您可以添加所需的任何内容。

&#13;
&#13;
.img-container,
.img-overlay {
  position: absolute;
  top: 0;
  left 0;
}

.img-container {
  overflow: hidden;
  }

.img-container img {
  max-width: 100%;
}

.img-overlay {
  width: 120%;
  height: 100%;
   -webkit-box-shadow: inset 0px 0px 25px 5px rgba(0,0,0,0.75);
  box-shadow: inset 0px 0px 25px 5px rgba(0,0,0,0.75);
  margin-left: -25px;
  padding: 0px 30px;
  color: white;
}
&#13;
<div class="img-container">
  <img src='http://blog.caranddriver.com/wp-content/uploads/2015/11/BMW-2-series.jpg' height="400px" />
  <div class="img-overlay">
    some text
   </div>
</div>
&#13;
&#13;
&#13;

编辑:如果您希望两者都有内容,您还可以为顶部和底部制作两个单独的叠加div,但这只是一个简单的示例。